To use SLF4J, it is required to include 3 jars SLF4J API (slf4j-api-x.x.x.jar), SLF4J bindings jar (eg. slf4j-log4j12-x.x.x.jar) and the actual logging framework (eg. log4j-1.2.17.jar).

Technologies used in this article :

  1. SLF4J

  2. log4j

  3. JDK 1.6

  4. Eclipse 3.7

Related Posts

1. Create a Java Project and a Class with 'main' method

Create a java project ('Log4jSLF4JHello') and a class ('Log4jSLF4JHello') with 'main' method


2. Copy slf4j & log4j jars

Create a 'lib' folder inside the project folder and copy the following jars 'slf4j-api-1.7.1.jar', 'slf4j-log4j12-1.7.1.jar' and 'log4j-1.2.17.jar' to the newly created 'lib' folder. These jars are already included in the full source code provided with this tutorial in the 'Download Source Code' section.


3. Configure Build Path

Add slf4j & log4j jars to the build path of your project as shown below.

Configure Build Path


4. Write Code

Modify your code as per the following code.

File :
package com.srccodes.examples;

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

 * @author Abhijit Ghosh
 * @version 1.0
public class Log4jSLF4JHello {
    private static Logger slf4jLogger = LoggerFactory.getLogger(Log4jSLF4JHello.class);

     * Print hello in log using log4j log implementation
     * @param name
    public void sayHello(String name) {"Hi, {}", name);"Welcome to the HelloWorld example of Log4j using SLF4J");

     * @param args
    public static void main(String[] args) {
        Log4jSLF4JHello slf4jHello = new Log4jSLF4JHello();
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. log4j configuration

Configure log4j.xml as per the requirement.

File : log4j.xml


6. Final project structure

Overall project structure will look like as shown below

slf4j overall project structure


7. 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 log4j.xml

File : myLogFile.log


Download Source Code

SrcCodes :