Logback

Language: Java

Logging

Logback was created by Ceki Gülcü, the founder of Log4j, to overcome the limitations of Log4j and provide a faster, more reliable, and natively configurable logging framework for Java applications. Logback is widely used in enterprise applications, Spring Boot projects, and microservices due to its simplicity and robust features.

Logback is a popular Java logging framework intended as a successor to Log4j. It provides powerful configuration options, fast performance, and a rich set of appenders and layouts for logging messages in various formats and destinations.

Installation

maven: Add dependency in pom.xml: <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.4.11</version> </dependency>
gradle: implementation 'ch.qos.logback:logback-classic:1.4.11'

Usage

Logback allows logging messages at different levels (TRACE, DEBUG, INFO, WARN, ERROR). It supports console, file, rolling file, and asynchronous appenders, with flexible XML or Groovy-based configuration.

Simple logging

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

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

    public static void main(String[] args) {
        logger.info("Application started");
        logger.debug("Debugging details");
        logger.error("An error occurred");
    }
}

Uses Logback via the SLF4J API to log messages at different levels.

Configuring logback.xml

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

    <root level="info">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>

Defines a console appender and sets the root logging level to INFO with a custom message pattern.

Rolling file appender

<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>logs/app.log</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>logs/app.%d{yyyy-MM-dd}.log</fileNamePattern>
        <maxHistory>30</maxHistory>
    </rollingPolicy>
    <encoder>
        <pattern>%d [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
</appender>

Logs messages to a file and rolls over daily, keeping logs for the last 30 days.

Using MDC for contextual logging

import org.slf4j.MDC;

MDC.put("userId", "12345");
logger.info("User logged in");
MDC.clear();

Adds contextual information (e.g., user ID) to logs using Mapped Diagnostic Context.

Async logging

<appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender">
    <appender-ref ref="FILE" />
</appender>

Wraps an existing appender with an asynchronous appender to improve performance for high-volume logging.

Error Handling

FileNotFoundException: Ensure log file paths are correct and the application has write permissions.
PatternLayout encoder errors: Check the logback pattern configuration and validate the syntax.

Best Practices

Use SLF4J API for logging to allow swapping underlying logging frameworks.

Avoid logging sensitive information in production logs.

Use appropriate log levels (DEBUG for development, INFO/WARN/ERROR for production).

Configure rolling appenders to prevent log files from growing indefinitely.

Leverage MDC or structured logging for better traceability.