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 :

Logback SLF4J Maven JDK 1.6 Eclipse 3.7

Related Posts

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

Specify Archetype Parameters as shown below

2. Add slf4j and Logback dependencies

Add slf4j and Logback dependencies into pom.xml

3. logback configuration

Add logback.xml and configure as per the requirement.

Note:

If you are switching to Logback from existing log4j then use 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.

File : logback.xml

4. Write Code

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

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.

File : LogbackHello.java

5. Final project structure

Overall project structure will look like as shown below

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

Download Source Code

References