Logback is an increasingly popular logging framework intended as a successor to the popular log4j project. It is designed by the founder of log4j. Logback offers many advantages over log4j like faster, smaller memory footprint, automatic reloading of configuration files, automatic compression of archived log files, conditional processing of configuration files and many more. For more details go through the following link Reasons to prefer logback over log4j.

This tutorial describes how to configure SLF4J and Logback as logging solution of an application.

Simple Logging Facade for Java (SLF4J) is an abstraction of different logging frameworks (eg. log4j, java.util.logging, commons logging etc.).

Logback is comprised of three modules logback-core, logback-classic and logback-access.

To integrate Logback with SLF4j, we need to include 3 jars SLF4J API (slf4j-api-x.x.x.jar), SLF4j bindings jar (eg. logback-classic-x.x.x.jar) and the actual logging framework (eg. logback-core-x.x.x.jar).

Technologies used in this article :

  1. Logback
  2. SLF4J
  3. Maven
  4. JDK 1.6
  5. Eclipse 3.7

1. Create Maven Project

Select from the menu File --> New --> Other --> Maven --> Maven Project ('logback').
Select Archetype (Group Id: 'org.apache.mavens.archetypes' and Artifact Id : 'maven-archetype-quickstart')
Select Maven Archetype

Specify Archetype Parameters as shown below
Select Maven Archetype Parameters

2. Add slf4j and Logback dependencies

Add slf4j and Logback dependencies into pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
 
    <groupId>com.srccodes.log</groupId>
    <artifactId>logback</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
 
    <name>logback</name>
    <url>http://maven.apache.org</url>
 
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <slf4j.version>1.6.6</slf4j.version>
        <logback.version>1.0.7</logback.version>
    </properties>
 
    <dependencies>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback.version}</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>${logback.version}</version>
        </dependency>
         
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

3. logback configuration

Add logback.xml and configure as per the requirement.
File: logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="fileAppender" class="ch.qos.logback.core.FileAppender">
        <file>c:/myLogFile.log</file>
        <append>true</append>
        <encoder>
            <pattern>%d [%thread] %-5level  %logger{35} - %msg%n</pattern>
        </encoder>
    </appender>
     
    <root level="TRACE">
        <appender-ref ref="fileAppender" />
    </root>
</configuration>

Note: If you are switching to Logback from existing log4j then use log4j.properties to logback.xml Translator to generate the logback.xml from existing log4j.properties.

4. Write Code

Create a java class ('LogbackHello') with a main method and modify code as shown below
File: LogbackHello.java

package com.srccodes.log;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
/**
 * 
 * @author Abhijit Ghosh
 * @version 1.0
 */
public class LogbackHello {
    private static final Logger slf4jLogger = LoggerFactory.getLogger(LogbackHello.class);
 
 
    /**
     * @param args
     */
    public static void main(String[] args) {
        slf4jLogger.trace("Hello World!");
         
        String name = "Abhijit";
        slf4jLogger.debug("Hi, {}", name);
        slf4jLogger.info("Welcome to the HelloWorld example of Logback.");
        slf4jLogger.warn("Dummy warning message.");
        slf4jLogger.error("Dummy error message.");
    }
}

Note: Please refer the 'slf4j FAQ' link in the 'References' section to know the usage of '{}' and to know how it helps in performance optimization in logging.

5. Final project structure

Overall project structure will look like as shown below
logback overall project structure

6. Run Your Code to Generate Log

On execution of the main method, log will be generated in the log file 'myLogFile.log' as configured in logback.xml
File: myLogFile.log

2012-11-21 14:26:14,987 [main] TRACE  com.srccodes.log.LogbackHello - Hello World!
2012-11-21 14:26:14,989 [main] DEBUG  com.srccodes.log.LogbackHello - Hi, Abhijit
2012-11-21 14:26:14,989 [main] INFO   com.srccodes.log.LogbackHello - Welcome to the HelloWorld example of Logback.
2012-11-21 14:26:14,990 [main] WARN   com.srccodes.log.LogbackHello - Dummy warning message.
2012-11-21 14:26:14,990 [main] ERROR  com.srccodes.log.LogbackHello - Dummy error message. 

Download SrcCodes

Sample codes used in this post is available in following link http://cdn.srccodes.com/c/112012/21/logback.zip

References