Adding SLF4J Logs to Akka

You might want to consider adding SLF4J plugin to your default Akka logs. This can help you standardize the logs and would help you in the better analysis of your logs.

Akka provides help on how you can plugin SLF4J into your akka application: http://doc.akka.io/docs/akka/snapshot/java/logging.html#SLF4J 

I implemented the suggested approach and am listing down the simplified steps for quick reference.

Add dependency

Add akka-slf4j plugin and logback-classic dependency to your build.

Eg: Add the following to your pom.xml

<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-slf4j</artifactId>
<version>2.3.9</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.2</version>
</dependency>

If you are using SBT, then your build.sbt would look like:

libraryDependencies += “com.typesafe.akka” % “akka-slf4j” % “2.3.9”,
libraryDependencies += “ch.qos.logback” % “logback-classic” % “1.1.2”

Enable SLF4JLogger for Akka

Update your application.conf (src/main/resources) with the following:

akka {
event-handlers = [“akka.event.slf4j.Slf4jEventHandler”]
loglevel = “INFO”
}

Add logback.xml

Add logback.xml to your classpath. That is, create a logback.xml at src/main/resources. The following is an example of logback.xml. You can find more info about how you can configure your logs with the various patterns at: http://logback.qos.ch/manual/layouts.html

<?xml version=”1.0″ encoding=”UTF-8″?>
<configuration>
<appender name=”CONSOLE” class=”ch.qos.logback.core.ConsoleAppender”>
<target>System.out</target>
<encoder>
<pattern>%d %X{akkaTimestamp} %-4r %-5level [%thread] %logger{0} %class{0} – %-5msg%n</pattern>
</encoder>
</appender>
<appender name=”FILE” class=”ch.qos.logback.core.FileAppender”>
<file>./log/akka.log</file>
<append>false</append>
<encoder>
<pattern>%d %X{akkaTimestamp} %-4r %-5level [%thread] %logger{0} %class{0} – %-5msg%n</pattern>
</encoder>
</appender>
<logger name=”akka” level=”DEBUG” />
<root level=”INFO”>
<appender-ref ref=”CONSOLE”/>
<appender-ref ref=”FILE”/>
</root>
</configuration>

Add Logs

Now you can add logs to your code, add the following to your scala code:

import akka.event.Logging

val log = Logging(context.system, this.getClass.getName)

log.info(“Info message”)

log.warning(“Warning message”)

log.debug(“Debug message”)

log.error(“Error message”)