by shigemk2

当面は技術的なことしか書かない

akka Logging

Logging in Akka is not tied to a specific logging backend. By default log messages are printed to STDOUT, but you can plug-in a SLF4J logger or your own logger. Logging is performed asynchronously to ensure that logging has minimal performance impact. Logging generally means IO and locks, which can slow down the operations of your code if it was performed synchronously.

Logging — Akka Documentation

ログのとり方。

import akka.event.Logging
 
class MyActor extends Actor {
  val log = Logging(context.system, this)
  override def preStart() = {
    log.debug("Starting")
  }
  override def preRestart(reason: Throwable, message: Option[Any]) {
    log.error(reason, "Restarting due to [{}] when processing [{}]",
      reason.getMessage, message.getOrElse(""))
  }
  def receive = {
    case "test" => log.info("Received test")
    case x      => log.warning("Received unknown message: {}", x)
  }
}

ソースコード。context.systemとthisは様式に沿っているらしい。

  /**
   * Obtain LoggingAdapter for the given logging bus and source object.
   *
   * The source is used to identify the source of this logging channel and
   * must have a corresponding implicit LogSource[T] instance in scope; by
   * default these are provided for Class[_], Actor, ActorRef and String types.
   * See the companion object of [[akka.event.LogSource]] for details.
   *
   * You can add your own rules quite easily, see [[akka.event.LogSource]].
   *
   * Note that this `LoggingAdapter` will use the [[akka.event.DefaultLoggingFilter]],
   * and not the [[akka.event.LoggingFilter]] configured for the system
   * (if different from `DefaultLoggingFilter`).
   */
  def apply[T: LogSource](bus: LoggingBus, logSource: T): LoggingAdapter = {
    val (str, clazz) = LogSource(logSource)
    new BusLogging(bus, str, clazz)
  }

  /**
   * Obtain LoggingAdapter with MDC support for the given actor.
   * Don't use it outside its specific Actor as it isn't thread safe
   */
  def apply(logSource: Actor): DiagnosticLoggingAdapter = {
    val (str, clazz) = LogSource(logSource)
    val system = logSource.context.system.asInstanceOf[ExtendedActorSystem]
    new BusLogging(system.eventStream, str, clazz, system.logFilter) with DiagnosticLoggingAdapter
  }