How to log from an Akka-based library with a logging adapter provided by the host application?

214 Views Asked by At

I'm making a small library - a single Flow really - and would like to do some debugging logging from its code. The library is going to be used from both Log4J2 and Logback -based applications. I would like the logging to "just happen".

What I've done:

All library dependencies are "provided":

libraryDependencies ++= Seq(
    "com.typesafe.akka" %% "akka-slf4j" % AkkaVersion,
    "com.typesafe.akka" %% "akka-stream" % AkkaVersion,
    "com.typesafe.akka" %% "akka-http" % "10.1.12"
).map(_ % Provided)       // those come from the application

I've read Akka Logging (Akka docs), but it's version 2.4.20. Is there similar for 2.6?

akka-slf4j provides the library with Logging and LoggingFactory classes. The way the logger is initialized in the library:

private val LOGGER = LoggerFactory.getLogger(this.getClass);

However, no logging happens. Console output, running on a host that provides Logback 1.2.3:

$ sbt test:run
[info] Loading settings for project global-plugins from plugins.sbt ...
[info] Loading global plugins from /Users/.../.sbt/1.0/plugins
[info] Loading project definition from /Users/.../myProject/project
[info] Loading settings for project ... from build.sbt ...
[info] Set current project to ... (in build file:...)
[info] running test.Main 10
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
SLF4J: Failed to load class "org.slf4j.impl.StaticMDCBinder".
SLF4J: Defaulting to no-operation MDCAdapter implementation.
SLF4J: See http://www.slf4j.org/codes.html#no_static_mdc_binder for further details.
...

From one of those links:

This error indicates that appropriate SLF4J binding could not be found on the class path. Placing one (and only one) of slf4j-nop.jar, slf4j-simple.jar, slf4j-log4j12.jar, slf4j-jdk14.jar or logback-classic.jar on the class path should solve the problem.

If I add slf4j-simple to the library dependencies, I get the logs but they are without coloring. It seems to me that I've fixed the logging in the library to use its own logging implementation - not the host's as I wished for. Is this correct? How to do this right?

Akka version is 2.6.5

1

There are 1 best solutions below

0
On

The reason was that SLF4J doesn't seem to look under the test scope.

Fixed it with this:

$ sbt update    # download dependencies
$ mkdir lib
$ ln -s ~/.m2/repository/ch/qos/logback/logback-core/1.2.3/logback-core-1.2.3.jar lib/
$ ln -s ~/.m2/repository/ch/qos/logback/logback-classic/1.2.3/logback-classic-1.2.3.jar lib/

Another approach I've seen somewhere on the Net but never realized was describing my problem involves making sub-projects. I found continuing to use test:run simplest.