简体   繁体   中英

Logging with slf4j and any other logging framework (log4j/java.util.logging)

In my project am using slf4j + log4j for logging. Am new to java and trying to understand how logging works. If I want to use some other logging framework other than log4j say java.util.logging, then I don't have to change any code since am using slf4j. I just need to remove the jar of log4j and add the binary of java.util.logging. I was trying to understand how it works differently when we are not changing any code.Please let me know if the question is not clear. I really appreciate if you could point me to some links or examples.

Ok for example am using slf4j and java.util.logging in the following example.

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

public class SLF4JHello {

    private final Logger slf4jLogger = LoggerFactory.getLogger(SLF4JHello.class);

    public void sayHello(String name){

        slf4jLogger.info("Hi,{}",name); 
        slf4jLogger.info("Welcome to the HelloWorld example of SLF4J");
    }

    public static void main(String[] args) {
        SLF4JHello slf4jHello = new SLF4JHello();
        slf4jHello.sayHello("srccodes.com");
    }
}

and I have the jars slf4j-api-1.7.8.jar and slf4j-jdk14-1.7.7-1.0.0 jar in the class path.

This will result in the following output in the console.


Feb 25, 2015 9:29:52 AM com.srccodes.examples.SLF4JHello sayHello INFO: Hi,srccodes.com    
Feb 25, 2015 9:29:52 AM com.srccodes.examples.SLF4JHello sayHello INFO: Welcome to the HelloWorld example of SLF4J

SLF4J is a simple facade for logging systems allowing the end-user to plug-in the desired logging system at deployment time.

My question is- Now if I want to switch to log4j instead of java.util.logging for the above code, I have to replace the jul jar with log4j jar and nothing has to be changed in the code. What would be the behaviour of the code now? will it still display the same output?

I mean how does the code work differently with the different logging frameworks?

The output of the different logging implementations that SLF4J delegates to depends on the configuration of the logging framework. Each framework can do different things.

How to configure the different frameworks is documented in the respective documentation. Log4j , Log4j2 , Logback docs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM