Everything Java

← Back to blog

Published on Sat May 03 2025 16:45:00 GMT+0000 (Coordinated Universal Time) by Purusothaman Ramanujam

Logging in Java: SLF4J and Logback Basics

Introduction

Logging is essential for understanding what your application is doing, diagnosing problems, and monitoring in production. In Java, SLF4J (Simple Logging Facade for Java) is the standard logging API, and Logback is a popular implementation that works seamlessly with SLF4J.

In this post, you’ll learn how to set up SLF4J and Logback, and use them for effective logging in your Java applications.

What are SLF4J and Logback?

Adding SLF4J and Logback to Your Project

Maven Dependencies

<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.4.11</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.9</version>
</dependency>

Gradle Dependencies

implementation 'ch.qos.logback:logback-classic:1.4.11'
implementation 'org.slf4j:slf4j-api:2.0.9'

Basic Usage

Creating a Logger

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LoggingExample {
private static final Logger logger = LoggerFactory.getLogger(LoggingExample.class);
public static void main(String[] args) {
logger.info("Application started");
logger.debug("Debugging details");
logger.warn("A warning message");
logger.error("An error occurred");
}
}

Logback Configuration

Logback is configured using an XML file named logback.xml in your src/main/resources directory. Here’s a simple example:

<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>

Logging Best Practices

  1. Use Placeholders: Avoid string concatenation in log messages.
    logger.info("User {} logged in", username);
  2. Log at the Right Level: Use debug for development, info for general events, warn for potential issues, and error for failures.
  3. Don’t Log Sensitive Data: Avoid logging passwords or personal information.
  4. Externalize Configuration: Use logback.xml for flexible log management.
  5. Use Markers and MDC: For advanced logging, use Markers and Mapped Diagnostic Context (MDC) to add context to logs.

Conclusion

SLF4J and Logback make logging in Java simple and powerful. With a few dependencies and a basic configuration, you can add robust logging to your applications. Explore advanced features like rolling files, custom appenders, and MDC as you grow more comfortable.

Resources

Written by Purusothaman Ramanujam

← Back to blog