登录Akka时如何缩写ActorRef的路径?

时间:2018-01-22 07:39:14

标签: scala logging akka actor

当我执行log.info("just a log message")时,我得到一个这样的日志字符串:

[INFO] [01/22/2018 18:28:31.950] [s-akka.actor.default-dispatcher-7] [akka://s/user/bob] just a log message

其中bob是actor引用的名称。

我想获得以下内容:

[INFO] [01/22/2018 18:28:31.950] [bob] just a log message

我该怎么做?如何配置akka或记录器以不在日志中包含所有样板信息?

2 个答案:

答案 0 :(得分:3)

虽然@ elm的回答和@ Sarvesh的评论让我走上正轨,但他们并没有完全回答我的问题。所以,我在这里发布了一个完整的解决方案。

build.sbt

libraryDependencies ++= Seq(
  "com.typesafe.akka" %% "akka-slf4j" % "2.5.9",
  "ch.qos.logback" % "logback-classic" % "1.2.3"
)

src/main/resources/reference.conf

akka {
  loggers = ["akka.event.slf4j.Slf4jLogger"]
  loglevel = "INFO"
}

src/main/resources/logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true">
    <appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
        <target>System.out</target>
        <encoder>
            <charset>UTF-8</charset>
            <Pattern>[%level] %d{HH:mm:ss.SSS} %message%n%xException{5}</Pattern>
        </encoder>
    </appender>

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>log/akka.log</file>
        <encoder>
            <charset>UTF-8</charset>
            <pattern>%d %-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
        </encoder>
    </appender>

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

然后创建ActorRefLogging.scala

trait ActorRefLogging { this: Actor =>
  // if self.toString() is "akka://s/user/bob#1234567"
  // then shortName is "bob"
  private val shortName = self.toString().split("/").last.split("#").head
  private val l = Logging(context.system, this)

  object log {
    def error(s: String): Unit = l.error(s"[$shortName] $s")
    def warning(s: String): Unit = l.warning(s"[$shortName] $s")
    def info(s: String): Unit = l.info(s"[$shortName] $s")
    def debug(s: String): Unit = l.debug(s"[$shortName] $s")
  }
}

然后混合演员中的特征并使用记录器:

class MyActor extends Actor with ActorRefLogging {
  def receive = {
    case m => log.info(s"Received: $m")
  }
}

答案 1 :(得分:1)

resources/logback.xml更新[%logger][%logger{0}],例如

<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
        <pattern>[%level] %d{yyyy:MM:dd HH:mm:ss.SSS} [%logger{0}] %message%n%xException{5}</pattern>
    </encoder>
</appender>