medium.com 10 min read Original Source

Mastering Java Logging Frameworks with Examples — Part 2

Overview

In the previous post, we introduced some of the most commonly used logging frameworks in Java including JUL, SLF4J, Logback, Log4J, Log4J2, in which SLF4J is a special one that provides a simple facade or wrapper API over different logging frameworks. In this post, we will take a deep look at how Log4J and Log4J 2 are used.

Log4j Security Vulnerabilities

It was big news a while ago in the Log4J and Java communities due to the Security Vulnerabilities of Log4j. In short, Apache Log4j2 versions 2.0-beta7 through 2.17.0 (excluding security fix releases 2.3.2 and 2.12.4) are vulnerable to a remote code execution (RCE) attack where an attacker with permission to modify the logging configuration file can construct a malicious configuration using a JDBC Appender with a data source referencing a JNDI URI which can execute remote code. This issue is fixed by limiting JNDI data source names to the java protocol in Log4j2 versions 2.17.1, 2.12.4, and 2.3.2.

Log4j 1.x mitigation

Log4j 1.x is not impacted by this vulnerability.

Log4j 2.x mitigation

Upgrade to Log4j 2.3.2 (for Java 6), 2.12.4 (for Java 7), or 2.17.1 (for Java 8 and later).

Log4j

Log4j is an open-source code project of Apache. With Log4j, we can control the destination of output logs, such as a console, file, or database. We can also control the format and define the level of each output log to control the log generation process.

Log4j provides seven log levels: TRACE, DEBUG, INFO, WARN, ERROR, FATAL, and OFF in ascending order of severity. If the log level is set to OFF, logging is disabled. Log4j supports configuration files in properties and xml formats. Log4j consists of three main components: logger, appender, and layout.

Log4j 1.x has reached End of Life in 2015 and is no longer supported. So we will not explain more about it, please continue to read to learn how to use Log4j 2 which is an advanced version of Log4j 1.x.

Log4J 2

Log4j 2 is an advanced version of Log4j 1.x and Logback. Log4j 2 uses some new technologies, such as lock-free and asynchronous, to improve the logging throughput and performance by a factor of 10 when compared with Log4j 1.x, solve some deadlock bugs, and make the configuration simpler and more flexible.

Log4j 2 offers a plugin architecture, which makes it extensible on demand and helps you implement your own appenders, loggers, and filters. Unlike other logging frameworks, Log4j 2 does not lose its previous log files during reconfiguration.

Log4j 2 uses the concurrency feature of Java 5 to execute locks at the lowest layer. This solves the deadlock problem in Log4j 1.x. Log4j 2 is based on the LMAX Disruptor library. In multi-thread scenarios, asynchronous loggers are about 10 times more efficient than those in existing logging frameworks.

Let’s try to perform the following tasks to get a deeper understanding of Log4J 2.

  1. Use only Log4j vs Log4j 2 + SLF4J for logging
  2. Print the log to both stdout (console) and file
  3. Configure different logging levels for different packages
  4. Check what happens if we provide different dependencies
  5. Check what happens if we don’t provide the logging configuration file (log4j2.xml)

Note, we excluded spring-boot-starter-logging from our project since it contains several logging frameworks to better demonstrate our examples.

implementation("org.springframework.boot:spring-boot-starter") {
   exclude("org.springframework.boot", "spring-boot-starter-logging")
}
implementation("org.springframework.boot:spring-boot-starter") {
   exclude("org.springframework.boot", "spring-boot-starter-logging")
}

Log4j 2 Appenders

Log4j 2 appender is responsible for delivering LogEvents to their destination. Some appenders only send LogEvents while others wrap other appenders to provide additional functionality. Let’s look at some of the appenders available in Log4j 2. Keep in mind that this is not a full list of appenders and to see all of them look at Log4j 2 appenders documentation.

  • ConsoleAppender — writes the data to System.out or System.err with the default begin the first one (a Java best practice when logging in containers)
  • FileAppender — appender that uses the FileManager to write the data to a defined file
  • RollingFileAppender — appender that writes data to a defined file and rolls over the file according to a defined policy
  • MemoryMappedFileAppender — added in version 2.1, uses memory-mapped files and relies on the operating system virtual memory manager to synchronize the changes in the file with the storage device
  • FlumeAppender — appender that writes data to Apache Flume
  • CassandraAppender — appender that writes data to Apache Cassandra
  • JDBCAppender — writes data to a database using standard JDBC driver
  • HTTPAppender — writes data to a defined HTTP endpoint
  • KafkaAppender — writes data to Apache Kafka
  • SyslogAppender — writes data to a Syslog-compatible destination
  • ZeroMQAppender — writes data to ZeroMQ
  • AsyncAppender — encapsulates another appender and uses a different thread to write data, which results in asynchronous logging

We will see how we use different appenders in the log4j2.xml below.

Configure log4j2.xml

Log4j 2 provides a default configuration that will be used if no custom configuration file is provided. This default configuration is designed to work in most situations, but it may not meet all of your specific logging needs.

If you choose to configure Log4j 2 using a log4j2.xml or log4j2.yml file, you can place the file in your application’s classpath (in our case main/java/resources), in the root of your application’s jar file, or in a directory specified by the log4j.configurationFile system property.

Here’s the log4j2.xml file that sets up a console and file appender with logging level info for the root logger, and a customized logger with a name com.example.javasandbox and logging level WARN.

<button data-code="

” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn">
    <Appenders>
        <Console name="console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </Console>
        <File name="file" fileName="log4j2.log">
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </File>
    </Appenders>
    <Loggers>
        <Root level="INFO">
            <AppenderRef ref="console" />
            <AppenderRef ref="file" />
        </Root>
        <Logger name="com.example.javasandbox" level="WARN">
        </Logger>
    </Loggers>
</Configuration>
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn">
    <Appenders>
        <Console name="console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </Console>
        <File name="file" fileName="log4j2.log">
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </File>
    </Appenders>
    <Loggers>
        <Root level="INFO">
            <AppenderRef ref="console" />
            <AppenderRef ref="file" />
        </Root>
        <Logger name="com.example.javasandbox" level="WARN">
        </Logger>
    </Loggers>
</Configuration>

Now, let’s add dependencies and write our Java code to utilize the configure file and generate some logs.

Using only Log4j 2

Log4j 2 can be thought of SLF4J with Logback. log4j-api is equivalent to SLF4J, and log4j-core is equivalent to Logback. So to use only Log4j 2, we can simply add the following dependency and log4j-api is included in the log4j-core. Note: it will not work if you only include the log4j-api dependency without log4j-core in your project.

The reason is that log4j-api is only an interface or API for the logging system, and it does not provide any implementation or functionality by itself. The actual implementation of the logging system is provided by log4j-core or other compatible logging frameworks.

implementation("org.apache.logging.log4j:log4j-core:2.17.1")
implementation("org.apache.logging.log4j:log4j-core:2.17.1")

Write the java code as below:

package com.example.javasandbox.logging;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Log4j2Example {
    private static final Logger logger = LogManager.getLogger(Log4j2Example.class);

    public static void main(String[] args) {
        logger.trace("This is a trace message.");
        logger.debug("This is a debug message.");
        logger.info("This is an info message.");
        logger.warn("This is a warn message.");
        logger.error("This is an error message.");
        logger.fatal("This is a fatal message");
    }
}
package com.example.javasandbox.logging;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Log4j2Example {
    private static final Logger logger = LogManager.getLogger(Log4j2Example.class);

    public static void main(String[] args) {
        logger.trace("This is a trace message.");
        logger.debug("This is a debug message.");
        logger.info("This is an info message.");
        logger.warn("This is a warn message.");
        logger.error("This is an error message.");
        logger.fatal("This is a fatal message");
    }
}

In this example, we first import the LogManager and Logger classes from the org.apache.logging.log4j package. We then create a logger instance for the Log4j2Example class using the LogManager.getLogger method.

To configure Log4j 2, you can create a log4j2.xml configuration file in your project’s classpath (e.g. main/java/resources). Here’s an example configuration file that sets the log level to INFO for the Log4j2Example class.

When we run the code, we should be able to see the following output on console and in log4j2.log file.

2023-03-04 22:20:38.994 [main] WARN  com.example.javasandbox.logging.Log4j2Example - This is a warn message.
2023-03-04 22:20:38.996 [main] ERROR com.example.javasandbox.logging.Log4j2Example - This is an error message.
2023-03-04 22:20:38.996 [main] FATAL com.example.javasandbox.logging.Log4j2Example - This is a fatal message
2023-03-04 22:20:38.994 [main] WARN  com.example.javasandbox.logging.Log4j2Example - This is a warn message.
2023-03-04 22:20:38.996 [main] ERROR com.example.javasandbox.logging.Log4j2Example - This is an error message.
2023-03-04 22:20:38.996 [main] FATAL com.example.javasandbox.logging.Log4j2Example - This is a fatal message

Using Log4j 2 + SLF4J

To use Log4J 2 and SLF4J together, we could add the dependencies below.

implementation("org.apache.logging.log4j:log4j-slf4j-impl:2.17.1") {
    exclude("org.apache.logging.log4j", "log4j-api") // this line is optional
}
implementation("org.apache.logging.log4j:log4j-core:2.17.1")
implementation("org.apache.logging.log4j:log4j-slf4j-impl:2.17.1") {
    exclude("org.apache.logging.log4j", "log4j-api") // this line is optional
}
implementation("org.apache.logging.log4j:log4j-core:2.17.1")

log4j-slf4j-impl is a bridge module that allows you to use Log4j 2 as the underlying logging implementation for SLF4J. It depends on both slf4j-api and log4j-core, but it provides a simplified API for users who are already familiar with SLF4J and prefer to use it for logging. Since log4j-slf4j-impl also includes log4j-api and slf4j-api, so we don’t need to explicitly include slf4j-api.

Let’s write the Java code.

package com.example.javasandbox.logging;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SLF4JExample {
    private static final Logger logger = LoggerFactory.getLogger(SLF4JExample.class);

    public static void main(String[] args) {
        logger.trace("This is a trace message.");
        logger.debug("This is a debug message.");
        logger.info("This is an info message.");
        logger.warn("This is a warn message.");
        logger.error("This is an error message.");
        // logger.fatal("This is a fatal message"); // Cannot resolve method 'fatal' in 'Logger'
    }
}
package com.example.javasandbox.logging;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SLF4JExample {
    private static final Logger logger = LoggerFactory.getLogger(SLF4JExample.class);

    public static void main(String[] args) {
        logger.trace("This is a trace message.");
        logger.debug("This is a debug message.");
        logger.info("This is an info message.");
        logger.warn("This is a warn message.");
        logger.error("This is an error message.");
        // logger.fatal("This is a fatal message"); // Cannot resolve method 'fatal' in 'Logger'
    }
}

If you take a closer look at the code and compare it with what we had when using only Log4J2, you will notice the following differences

  1. Import org.apache.logging.log4j.xxx vs org.slf4j.xxx
  2. Get logger via LogManager.getLogger vs LoggerFactory.getLogger
  3. logger.trace is not available in SLF4J API.

Similarly, we will get the following output on the console and in the file if we use the same log4j2.xml.

2023-03-04 22:49:57.603 [main] WARN  com.example.javasandbox.logging.SLF4JExample - This is a warn message.
2023-03-04 22:49:57.609 [main] ERROR com.example.javasandbox.logging.SLF4JExample - This is an error message.
2023-03-04 22:49:57.603 [main] WARN  com.example.javasandbox.logging.SLF4JExample - This is a warn message.
2023-03-04 22:49:57.609 [main] ERROR com.example.javasandbox.logging.SLF4JExample - This is an error message.

What happens if we only include log4j-api when using only Log4J 2?

If we only add log4j-api as the dependency and use the same code and log4j2.xml as in Using only Log4J 2, we will see the following messages on the console only.

ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console...
ERROR Log4j2Example This is an error message.
FATAL Log4j2Example This is a fatal message
ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console...
ERROR Log4j2Example This is an error message.
FATAL Log4j2Example This is a fatal message

As we can see from the result, if we only provide log4j-api without log4j-core, Log4J 2 will just use the SimpleLogger which defaults the logging level to Error and no timestamp nor thread name is printed.

What happens if we use different dependencies when using Log4J 2 + SLF4J?

Previously we have used pattern 1 below, let’s see how it behaves when trying different dependencies strategies.

// Pattern 1 (recommended)
implementation("org.apache.logging.log4j:log4j-slf4j-impl:2.17.1") {
    exclude("org.apache.logging.log4j", "log4j-api") // this line is optional
}
implementation("org.apache.logging.log4j:log4j-core:2.17.1")

// Pattern 2, compile error
implementation("org.apache.logging.log4j:log4j-slf4j-impl:2.17.1") {
    exclude("org.apache.logging.log4j", "log4j-api")
}

// Pattern 3, same result as pattern 1
implementation("org.apache.logging.log4j:log4j-slf4j-impl:2.17.1")

// Pattern 4, no logging
implementation("org.slf4j:slf4j-api:1.7.36")
implementation("org.apache.logging.log4j:log4j-api:2.17.1")

// Pattern 5, no logging
implementation("org.slf4j:slf4j-api:1.7.36")
implementation("org.apache.logging.log4j:log4j-core:2.17.1")
// Pattern 1 (recommended)
implementation("org.apache.logging.log4j:log4j-slf4j-impl:2.17.1") {
    exclude("org.apache.logging.log4j", "log4j-api") // this line is optional
}
implementation("org.apache.logging.log4j:log4j-core:2.17.1")

// Pattern 2, compile error
implementation("org.apache.logging.log4j:log4j-slf4j-impl:2.17.1") {
    exclude("org.apache.logging.log4j", "log4j-api")
}

// Pattern 3, same result as pattern 1
implementation("org.apache.logging.log4j:log4j-slf4j-impl:2.17.1")

// Pattern 4, no logging
implementation("org.slf4j:slf4j-api:1.7.36")
implementation("org.apache.logging.log4j:log4j-api:2.17.1")

// Pattern 5, no logging
implementation("org.slf4j:slf4j-api:1.7.36")
implementation("org.apache.logging.log4j:log4j-core:2.17.1")

In pattern 2, we moved slf4j-core which in theory is required, and see the following error when compiling the code.

<button data-code="Failed to instantiate SLF4J LoggerFactory
Reported exception:
java.lang.NoClassDefFoundError: org/apache/logging/log4j/spi/AbstractLoggerAdapter
at java.base/java.lang.ClassLoader.defineClass1(Native Method)
at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1017)
at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:174)
at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:800)
at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:698)
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:621)
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:579)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
at org.slf4j.impl.StaticLoggerBinder.(StaticLoggerBinder.java:36)
at org.slf4j.LoggerFactory.bind(LoggerFactory.java:150)
at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:124)
at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:417)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:362)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:388)” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

Failed to instantiate SLF4J LoggerFactory
Reported exception:
java.lang.NoClassDefFoundError: org/apache/logging/log4j/spi/AbstractLoggerAdapter
 at java.base/java.lang.ClassLoader.defineClass1(Native Method)
 at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1017)
 at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:174)
 at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:800)
 at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:698)
 at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:621)
 at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:579)
 at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
 at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
 at org.slf4j.impl.StaticLoggerBinder.<clinit>(StaticLoggerBinder.java:36)
 at org.slf4j.LoggerFactory.bind(LoggerFactory.java:150)
 at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:124)
 at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:417)
 at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:362)
 at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:388)
Failed to instantiate SLF4J LoggerFactory
Reported exception:
java.lang.NoClassDefFoundError: org/apache/logging/log4j/spi/AbstractLoggerAdapter
 at java.base/java.lang.ClassLoader.defineClass1(Native Method)
 at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1017)
 at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:174)
 at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:800)
 at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:698)
 at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:621)
 at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:579)
 at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
 at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
 at org.slf4j.impl.StaticLoggerBinder.<clinit>(StaticLoggerBinder.java:36)
 at org.slf4j.LoggerFactory.bind(LoggerFactory.java:150)
 at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:124)
 at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:417)
 at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:362)
 at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:388)

In pattern 3, we removed log4j-core again but didn’t exclude log4j-api, somehow it worked the same as pattern 1. It’s possible that log4j-slf4j-impl is able to find a compatible version of Log4j on the classpath when log4j-api is there.

In both patterns 4 and 5, we see the output below, and no logging is performed. If we compare it with pattern 3, we can conclude that log4j-slf4j-impl is required for SLF4J to find the Log4J implementation.

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.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

What happens if we don’t provide log4j2.xml?

If we provide a log4j2.xml file or with a different file name and not telling Java, Log4j 2 will use its default configuration, which includes the following:

  • A console appender that logs messages at the ERROR level or higher to the console (stdout)
  • A root logger that logs messages at the ERROR level or higher using the console appender

This means that you will still be able to log messages using the default console appender, but you won’t be able to configure any additional appenders or loggers. When we rerun the code above, we will see the following on the console.

// Using only Log4J2
23:09:39.913 [main] ERROR com.example.javasandbox.logging.Log4j2Example - This is an error message.
23:09:39.916 [main] FATAL com.example.javasandbox.logging.Log4j2Example - This is a fatal message

// Using Log4J2 + SLF4J
23:13:13.053 [main] ERROR com.example.javasandbox.logging.SLF4JExample - This is an error message.
// Using only Log4J2
23:09:39.913 [main] ERROR com.example.javasandbox.logging.Log4j2Example - This is an error message.
23:09:39.916 [main] FATAL com.example.javasandbox.logging.Log4j2Example - This is a fatal message

// Using Log4J2 + SLF4J
23:13:13.053 [main] ERROR com.example.javasandbox.logging.SLF4JExample - This is an error message.

SLF4J with multiple logging implementations

Due to the logging packages might be included in your classpath transparently by thrid-party dependencies, there is a chance that when you use SLF4J API but there are multiple logging frameworks (e.g. Log4J2 and Logback) available under the hood. Suppose we have the following dependencies and the Java code.

// Log4J2 + SLF4J
implementation("org.apache.logging.log4j:log4j-slf4j-impl:2.17.1") {
  exclude("org.apache.logging.log4j", "log4j-api")
}
implementation("org.apache.logging.log4j:log4j-core:2.17.1")

// logback
implementation("ch.qos.logback:logback-classic:1.2.3")
package com.example.javasandbox.logging;

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

public class SLF4JExample {
    private static final Logger logger = LoggerFactory.getLogger(SLF4JExample.class);

    public static void main(String[] args) {
        logger.trace("This is a trace message.");
        logger.debug("This is a debug message.");
        logger.info("This is an info message.");
        logger.warn("This is a warn message.");
        logger.error("This is an error message.");
    }
}
// Log4J2 + SLF4J
implementation("org.apache.logging.log4j:log4j-slf4j-impl:2.17.1") {
  exclude("org.apache.logging.log4j", "log4j-api")
}
implementation("org.apache.logging.log4j:log4j-core:2.17.1")

// logback
implementation("ch.qos.logback:logback-classic:1.2.3")
package com.example.javasandbox.logging;

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

public class SLF4JExample {
    private static final Logger logger = LoggerFactory.getLogger(SLF4JExample.class);

    public static void main(String[] args) {
        logger.trace("This is a trace message.");
        logger.debug("This is a debug message.");
        logger.info("This is an info message.");
        logger.warn("This is a warn message.");
        logger.error("This is an error message.");
    }
}

In our log4j2.xml and logback.xml, we added log4j2and logback to distinguish different loggers.

<button data-code="// in log4j2.xml

// in logback.xml
[logback] %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} – %msg%n” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

// in log4j2.xml
<PatternLayout pattern="[log4j2] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />

// in logback.xml
<pattern>[logback] %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
// in log4j2.xml
<PatternLayout pattern="[log4j2] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />

// in logback.xml
<pattern>[logback] %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>

When we run the code, we will see the following on the console, and the first two lines are also written to file log4j2.log.

It happens because we have multiple SLF4J bindings (i.e., implementations of the SLF4J API) on our classpath, and they conflict with each other.

In your case, both logback-classic and log4j-slf4j-impl provide logging implementations. This can lead to conflicts and unexpected behavior, since SLF4J may choose to use one binding over the other depending on the order in which they appear on the classpath, in this case, Log4J 2 is picked.

[log4j2] 2023-03-04 23:50:38.346 [main] WARN  com.example.javasandbox.logging.SLF4JExample - This is a warn message.
[log4j2] 2023-03-04 23:50:38.348 [main] ERROR com.example.javasandbox.logging.SLF4JExample - This is an error message.
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/Users/peng.yang/.gradle/caches/modules-2/files-2.1/org.apache.logging.log4j/log4j-slf4j-impl/2.17.1/84692d456bcce689355d33d68167875e486954dd/log4j-slf4j-impl-2.17.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/peng.yang/.gradle/caches/modules-2/files-2.1/ch.qos.logback/logback-classic/1.2.3/7c4f3c474fb2c041d8028740440937705ebb473a/logback-classic-1.2.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.apache.logging.slf4j.Log4jLoggerFactory]
[log4j2] 2023-03-04 23:50:38.346 [main] WARN  com.example.javasandbox.logging.SLF4JExample - This is a warn message.
[log4j2] 2023-03-04 23:50:38.348 [main] ERROR com.example.javasandbox.logging.SLF4JExample - This is an error message.
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/Users/peng.yang/.gradle/caches/modules-2/files-2.1/org.apache.logging.log4j/log4j-slf4j-impl/2.17.1/84692d456bcce689355d33d68167875e486954dd/log4j-slf4j-impl-2.17.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/peng.yang/.gradle/caches/modules-2/files-2.1/ch.qos.logback/logback-classic/1.2.3/7c4f3c474fb2c041d8028740440937705ebb473a/logback-classic-1.2.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.apache.logging.slf4j.Log4jLoggerFactory]

Logging framework dependencies summary

Let’s summarize the logging dependencies we have used so far including the one (spring-boot-stater-logging) that had been excluded in the beginning. The following is the architecture for different logging frameworks.

Let’s enable all of them.

// include spring-boot-starter-logging
implementation("org.springframework.boot:spring-boot-starter-logging")

// slf4j-api
implementation("org.slf4j:slf4j-api:1.7.36")

// log4j
implementation("org.apache.logging.log4j:log4j-slf4j-impl:2.17.1")
implementation("org.apache.logging.log4j:log4j-core:2.17.1")
implementation("org.apache.logging.log4j:log4j-api:2.17.1")

// logback
implementation("ch.qos.logback:logback-classic:1.2.3")
// include spring-boot-starter-logging
implementation("org.springframework.boot:spring-boot-starter-logging")

// slf4j-api
implementation("org.slf4j:slf4j-api:1.7.36")

// log4j
implementation("org.apache.logging.log4j:log4j-slf4j-impl:2.17.1")
implementation("org.apache.logging.log4j:log4j-core:2.17.1")
implementation("org.apache.logging.log4j:log4j-api:2.17.1")

// logback
implementation("ch.qos.logback:logback-classic:1.2.3")

And here is our dependency tree.

The spring-boot-starter-logging dependency includes a set of logging libraries that are commonly used with Spring Boot applications, including SLF4J, Logback, Log4j, and JUL.

The slf4j-api dependency provides the SLF4J API, which is a facade for various logging frameworks, including Logback and Log4j.

The log4j-core and log4j-api dependencies provide the Log4j implementation of the SLF4J API. The log4j-slf4j-impl dependency is an adapter that allows Log4j to work with the SLF4J API.

The logback-classic dependency provides the Logback implementation of the SLF4J API.

In summary, the dependencies work together to provide a common logging interface (SLF4J), with different implementations (Log4j, Logback, and JUL) available as options. The spring-boot-starter-logging includes both Log4j Logback and JUL, but you can choose to use one or the other by excluding the dependency you don’t want.

Conclusion

In this post, we mainly demonstrated how to use Log4J with and without SLF4J and noticed some differences in using them.

We also experimented with different scenarios by trying different dependencies and omitting log4j2.xml file. Lastly, we summarized the dependencies that we have used so far.

Although there are many logging options out there, SLF4J as the facade for various logging frameworks including the popular logback and log4j2 is very handy and you shouldn’t go wrong with using it.

Mastering Logging Frameworks Series

References