How to make java.util.logging send logs to Logback?

Nathan Russell picture Nathan Russell · Jan 11, 2017 · Viewed 8.3k times · Source

I'm working on an app that logs using the slf4j api:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

...

private static final Logger LOG = LoggerFactory.getLogger(FreemarkerEmailPreviewGenerator.class);

...

LOG.error("Error generating email preview", e);

(Code above posted to show classes and packages in use, but pretty standard stuff.)

We use logback configured as follows:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>[%d{HH:mm:ss.SSS}] [%thread] [%-5level %logger{26} - %msg]%n
            </pattern>
        </encoder>
    </appender>

    <root>
        <level value="debug" />
        <appender-ref ref="STDOUT" />
    </root>

</configuration>

Some of our code makes use of 3rd party libraries that logs with java.util.logging - specifically freemarker. As you can see from the following console log entries, both logback and j.u.l are logging to the console, but they are not using the same config (the logback entries use our pattern, the j.u.l ones don't)

[12:24:38.842] [pool-2-thread-19] [INFO  u.o.n.r.l.s.e.t.TemplateLoaderFromService - Finding template workflow/mail/templates/common/workflow-macros.ftl]
[12:24:38.859] [pool-2-thread-19] [INFO  u.o.n.r.l.s.e.t.TemplateLoaderFromService - Loaded template workflow/mail/templates/common/workflow-macros.ftl as /workflow/mail/templates/common/workflow-macros.ftl from RegistryMailTemplateService.]
11-Jan-2017 12:24:38 freemarker.log.JDK14LoggerFactory$JDK14Logger error
SEVERE:

Expression domainContact is undefined on line 9, column 74 in workflow/mail/templates/common/workflow-macros.ftl.
The problematic instruction:
----------
==> ${domainContact.name} [on line 9, column 72 in workflow/mail/templates/common/workflow-macros.ftl]

Is it possible to make j.u.l logging use the logback config so that we have a single consistent logging config for the whole app?

Answer

King Nike picture King Nike · Jan 11, 2017

Your application needs to have the following jars:

Application -> Freemarker -> java.util.logging -> SLF4J Api: jul-to-slf4j.jar

Application -> SLF4J API: slf4j-api.jar

SLF4J API -> logback: logback-classic.jar and logback-core.jar

Since your application already contains slf4j-api.jar and logback-classic.jar, you probably only have to add the jul-to-slf4j.jar

If you use maven:

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>jul-to-slf4j</artifactId>
    <version>1.7.22</version>
</dependency>

<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.1.8</version>
</dependency>

logback classic will transitively add logback-core and slf4j-api