Log4j 2 / SLF4J for Java: Complete Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

What is this library and why is it needed



Log4j 2 and SLF4J are two interconnected logging libraries for Java that are the de facto standard in the world of enterprise development. SLF4J (Simple Logging Facade for Java) is a facade (abstraction) that provides a unified API for various logging frameworks. Log4j 2 is one of the most powerful and high-performance implementations of this API.



Why is this needed? Logging is the process of recording information about an application's operation: errors, warnings, informational messages, debug information. Without a logging system, developers are forced to use System.out.println(), which leads to:

  • Inability to flexibly manage output (enable/disable logs for different parts of the application)
  • Lack of logging levels (INFO, WARN, ERROR, DEBUG)
  • Performance issues (string concatenation even when logs are disabled)
  • Lack of output formats (date, time, class name, thread)


Log4j 2 solves all these problems. It supports asynchronous logging, filters, appenders (output to file, console, database, network), log rotation, and many other advanced features. SLF4J allows you to switch from Log4j 2 to Logback or java.util.logging without changing code if needed.



Installation



For Java projects, installation is done via Maven or Gradle build systems. Unlike Python (pip) or Node.js (npm), Java uses dependency management through configuration files.



Maven (pom.xml)

<!-- SLF4J API + Log4j 2 as implementation --><dependency>    <groupId>org.apache.logging.log4j</groupId>    <artifactId>log4j-slf4j-impl</artifactId>    <version>2.20.0</version></dependency>

<!-- Log4j 2 Core API (if not using SLF4J) --><dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.20.0</version></dependency>


Gradle (build.gradle)

dependencies {    implementation 'org.apache.logging.log4j:log4j-slf4j-impl:2.20.0'    implementation 'org.apache.logging.log4j:log4j-core:2.20.0'}


After adding the dependencies, create a configuration file log4j2.xml in the src/main/resources folder:

<?xml version="1.0" encoding="UTF-8"?><Configuration status="WARN">    <Appenders>        <Console name="Console" target="SYSTEM_OUT">            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>        </Console>    </Appenders>    <Loggers>        <Root level="info">            <AppenderRef ref="Console"/>        </Root>    </Loggers></Configuration>


Quick start with code example



Create a simple Java class for demonstration:

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

public class QuickStart { // Create a logger for the current class private static final Logger logger = LoggerFactory.getLogger(QuickStart.class);

public static void main(String[] args) { logger.info("Application started"); logger.debug("This is a debug message"); logger.warn("Warning: resources are running low"); logger.error("Critical error: {}", "division by zero");

try { int result = 10 / 0; } catch (ArithmeticException e) { logger.error("Error during calculation", e); } }}


The console output will look like this:

14:30:15.123 [main] INFO  QuickStart - Application started14:30:15.125 [main] WARN  Q                    

Recommendations