我们的Akka项目依赖于其他一些非akka代码。从此代码中,我们获取记录器的方法是调用org.slf4j.LoggerFactory.getLogger(ThisClass.class)

我想获得事件发生的时间和地点的实时和真实线程,包括在日志打印中,因此我获取akkaTimestamp和sourceThread的值,如下所示:

log4j.appender.console.layout.ConversionPattern=[%-5p] [%X{akkaTimestamp}] [%X{sourceThread}] %c{5}: %m%n


问题在于从MDC提取的这些值在从非Akka记录器发送的打印物中不可用。

他们说Here


最好在应用程序的非Akka部分中使用sourceThread MDC值,以使此属性在日志中始终可用。


但是他们从不说/

最佳答案

正如Konrad所说,它并不那么复杂。这对我有用:

import akka.util.Helpers
import ch.qos.logback.core.ConsoleAppender
import org.slf4j.MDC

/**
 * Decorates MDC with same keys as Akka in
 * <a href="https://github.com/akka/akka/blob/master/akka-slf4j/src/main/scala/akka/event/slf4j/Slf4jLogger.scala#L89">Slf4jLogger</a>
 * So that logging messages dispatched from non-akka threads has same data.
 */
class AkkaCompatibleConsoleAppender[E] extends ConsoleAppender[E] {

  val mdcThreadAttributeName = "sourceThread"
  val mdcAkkaTimestamp = "akkaTimestamp"

  override def append(eventObject: E): Unit = {
    try {
      MDC.put(mdcAkkaTimestamp, Helpers.currentTimeMillisToUTCString(System.currentTimeMillis()))
      MDC.put(mdcThreadAttributeName, Thread.currentThread().getName)
      super.append(eventObject)
    } finally {
      MDC.remove(mdcAkkaTimestamp)
      MDC.remove(mdcThreadAttributeName)
    }
  }
}


然后在logback.xml中:

<appender name="STDOUT" class="agordo.server.AkkaCompatibleConsoleAppender">
    <encoder>
        <pattern>%X{akkaTimestamp} %-5level %logger{36} %X{sourceThread} %X{akkaSource} - %msg%n</pattern>
    </encoder>
</appender>

08-28 03:35