Akka(JVM)在ActorSystem之前初始化记录器

时间:2017-02-20 15:43:25

标签: scala logging akka

我有一个应用程序需要调用一些外部系统(解密敏感信息以保持简短),然后才能创建actor系统将使用的配置。

是否可以在我的流程开始时初始化记录器,以便监控/调查工具可以在与外部系统的通信出错时访问日志?

// the following call will modify the config from a secret id read in the conf
// and write the value "redis.password" after getting the value from an Azure Keyvault
val updatedConf = KeyVaultHelper.decryptFromKeyVault(ConfigFactory.load("application"),
  Map(
    "azure.keyvault.redis.password.secret-id",
    "redis.password"
  ))

// now we initialize the actor system with the updated conf
// and the logging system will be initialized
val system = ActorSystem("ClusterSystem", updatedConf)

1 个答案:

答案 0 :(得分:1)

要实现此目的,您可以使用akka-slf4j库以及推荐的日志记录后端logback。需要配置两件事。

配置记录器的logback.xml文件:

<!-- src/main/resources/logback.xml -->
<configuration>
  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%date{ISO8601} %-5level %logger{36} %X{sourceThread} - %msg%n</pattern>
    </encoder>
  </appender>
  <root level="debug">
    <appender-ref ref="STDOUT" />
  </root>
</configuration>

还必须从typesafe配置配置slf4j记录器:

# src/main/resources/application.conf
akka {
  loggers = ["akka.event.slf4j.Slf4jLogger"]
  loglevel = "DEBUG"
  logging-filter = "akka.event.slf4j.Slf4jLoggingFilter"
} 

请查看代码示例以测试配置。

object LoggingTest extends App {
  // Do all decryption logging here
  val logger = LoggerFactory.getLogger(getClass)
  logger.debug("Starting application. Decrypting info from config")

  // Now you boot the system which will use the same logging config
  val system = ActorSystem()
  val actor = system.actorOf(Props[Echo])

  actor ! "hello"
}

class Echo extends Actor {
  override def receive: Receive = {
    case message =>
      context.system.log.debug(s"echo $message")
  }
}

我使用了以下akka-actor&amp; akka-slf4j 2.4.17和ch.qos.logback 1.1.3。

如果您还有其他问题,请与我们联系。