13
12

More than 5 years have passed since last update.

Sprayでログの設定をする

Posted at

Sprayを利用したアプリケーションの実装を行う際、ログ出力は必須となりますが、そのあたりに関する設定のメモ。

日本語でSprayの記事って少ないですね。

LoggingContextにありますが、AkkaのLoggingAdapterをラップしてるようです。したがって、Akkaと同じ設定で利用できます。

ちなみに、ビルドにはsbtを利用している前提です。

logback.xml

logback.xmlsrc/main/resourcesに置きます。内容はLogbackのための設定なので、詳細については別の資料とかを見たほうが良いかと。

サンプルで、以下のを用意しました。

<configuration>

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>application-debug.log</file>
        <append>true</append>
        <!-- encoders are assigned the type
             ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
        <encoder>
            <pattern>%d{yyyy/dd/MM HH:mm:ss.SSS} %-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
        </encoder>
    </appender>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yyyy/dd/MM HH:mm:ss.SSS} %-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="DEBUG">
        <appender-ref ref="FILE" />
        <appender-ref ref="STDOUT"/>
    </root>
</configuration>

build.sbt

依存関係を追加します

libraryDependencies ++= {
  val akkaV = "2.3.0"
  Seq(
    "ch.qos.logback" % "logback-classic" % "1.1.2",
    "com.typesafe.akka" %% "akka-slf4j" % akkaV
  )
}

バージョンについては適当なものを設定します。

application.conf

application.confでAkkaの設定をします。

akka {
  loggers = ["akka.event.slf4j.Slf4jLogger"]
  event-handlers = ["akka.event.slf4j.Slf4jEventHandler"]
  loglevel = DEBUG
}

ログ出力

Actorにサブクラスなどで

import spray.util.LoggingContext


val logging = LoggingContext.fromActorRefFactory
logger.debug("This is log")

とりあえずログの出力ができました。

便利ですね。

13
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
12