Detailed understanding and related usage of slf4j log4j logback relationship

Source: Internet
Author: User
Tags log4j
the relationship between slf4j log4j Logback What is the simple Logging façade for Java.

Generally speaking is slf4j is a series of log interface, and log4j Logback is the specific implementation of the log framework. Next, we'll look at their relationship in detail in the official document.

The simple Logging façade for Java (SLF4J) serves as a simple façade or abstraction for various Logging framework s, such as java.util.logging, logback and log4j. SLF4J allows the end-user to plug in the desired framework at logging time. Note This slf4j-enabling your library/application implies addition of a single mandatory dependency, namely SLF4J -api-1.7.21.jar.

This passage of the official document has clearly described the relationship between the three. SLF4J, a simple log façade, is an abstraction of the log frame. and log4j and Logback are several of the many log frames.

Here are a few lines of simple code to verify.

public class Program {public
    static void Main (string[] args) {
        Logger Logger = Loggerfactory.getlogger (program.c LASS);
        Logger.info ("Hello World");
    }

From the results of the operation can be seen, because no specific logger implementation, unable to output the log in the console. In other words, we need to bind a log frame in the concrete development to use slf4j properly. log4j and Logback.

and log4j and Logback are two popular log frames. But the two are different. Log4j is an open source log component implemented by Apache. (wrapped implementations) Logback is also designed by the log4j author and has better features to replace a log4j log frame. is the SLF4J realization of the original life. (Native implementations)


The diagram above can see the application's call relationship to the log frame. The application invokes the SLF4J API, and the output of the log is ultimately implemented by the underlying log framework. This picture also log4j the difference between the Logback and the other.

Description of Logback in official documents

NATIVE Implementation There are also slf4j bindings external to the SLF4J project, e.g. Logback which implements. slf4j natively. Logback ' s Ch.qos.logback.classic.Logger class is a direct implementation of SLF4J ' s Org.slf4j.Logger interface. Thus, using SLF4J in conjunction with logback involves Strictly zeromemory and computational overhead.

You can see that the logback is a direct implementation of the SLF4J interface, which does not consume memory and compute overhead. The log4j is not a native implementation of SLF4J, so the SLF4J API requires an adaptation layer when calling log4j.

Summary: slf4j is a Java log façade that implements some of the common api,log4j and logback log frames that are specific to the log framework. They can be used separately, or they can be bound slf4j together. Used alone. Call the framework's own methods to output log information, respectively. Bind the slf4j to use together. Call the SLF4J API to enter the log information, using the underlying log framework regardless of the configuration file that requires the underlying framework

Obviously here we do not recommend using the log frame alone. Assuming that log4j is already in use in the project, we now load a class library that relies on another log framework. This time we need to maintain two log frames, which is a very troublesome thing. The use of slf4j is different, because the application call of the abstraction layer of the API, and the underlying log framework is irrelevant, so you can arbitrarily replace the log frame. Use the SLF4J binding log system to the advantage of the software engineering perspective. Abstract, decoupled, easy to maintain. Please refer to the above example. Syntax design angle. SLF4J have {} placeholders, and log4j need to use "+" to connect strings, which is not conducive to reading, while consuming memory (heap memory). Detailed description can refer to: http://www.importnew.com/7450.html log4j and Logback

As a log4j developer, the log4j must be not unfamiliar, he is an open source log framework for Apache. and logback relative to log4j, update a little, is by the author of log4j design Implementation, the first version is 2011 launched. In terms of design and implementation, Logback relative log4j has improved a lot. But the use of the two is little different. The following are the advantages of Logback: Faster execution speed, full testing logback-classic very naturally slf4j rich extension document can use the XML configuration file or groovy to automatically reload the configuration file gracefully recover from I/O errors Automatically purge old log archives automatically compress archived log files More benefits can be referred to the official documentation. English version of Chinese version

Above, from the performance angle, can migrate from log4j to Logback as soon as possible. use of slf4j binding log4j

As the log4j is now used more, so introduce his basic usage. IDE Related Settings

Here we use the IntelliJ IDEA2016.1 and maven. Add dependent dependencies in Pom.xml.

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactid>slf4j-log4j12</ artifactid>
    <version>1.7.21</version>
</dependency>

Three jar packs are added automatically. configuration file

log4j normal operation requires configuration file, Profile type: log4j configuration file can be Log4j.xml or log4j.properties. You need to configure root, Appender, layout, and other information for it.

Although most tutorials on the Web are configured with Log4j.properties (key-value pairs), I personally feel that using XML configuration, nodes are clearer, and there are code hints under idea that can reduce the probability of configuration errors. Below I will not specifically talk about the configuration file, only to mention a few key places. Root logger and a appender must be configured.

Log output level, from high to low

    FATAL        
    ERROR      
    WARN        
    INFO        
    DEBUG    

The configuration file is given below.

<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE log4j:configuration SYSTEM "LOG4J.DTD" > <log4j:configuration> <!--A number of Appender definitions--> -org.apache.log4j.consoleappender output to console--> <appender name= "MyConsole" Org.apache.log4j.ConsoleAppender "> <!--output format--> <layout class=" Org.apache.log4j.PatternLayout "&
            Gt <param name= "Conversionpattern" value= "%-d{yyyy-mm-dd hh:mm:ss,sss} [%c]-[%p]%m%n"/>  ;/layout> </appender> <!--Org.apache.log4j.DailyRollingFileAppender produces a log file every day--> <appender Name= "MyFile" class= "Org.apache.log4j.DailyRollingFileAppender" > <param name= "File" value= "Output.log"/> <!--file location--> <param name= "Append" value= "true"/><!--select append--> <layout class= "Org.apach E.log4j.patternlayout "> <param name=" Conversionpattern "value="%-d{yyyy-mm-DD hh:mm:ss,sss} [%c]-[%p]%m%n "/> </layout> </appender> <!--org.apache.log4j.RollingFi Leappender Scroll log file output file size when it reaches a certain size new file--> <!--<appender name= "MyFile" class= " Org.apache.log4j.RollingFileAppender "> <param name=" File "value=" D:/output.log "/> <param name = "Append" value= "true"/> <param name= "maxfilesize" value= "500KB"/> <param name= "Maxbackupinde X "value="/> <layout class= "org.apache.log4j.PatternLayout" > <param name= "Conversionpa" 
        Ttern "value="%p (%c:%l)-%m%n "/> </layout> </appender>--> <!--Output the class logs from each package to a different log file
        This makes it easy to categorize the logs. This setting allows you to add a log of the business logic to the database.
    Play the role of filtering--> <!--This configuration means that the log with the package name "COM.ZJUT.A1" and the priority for debug is handled by myfile this appender. --> <category name= "com.zjut.a1" > <priority value= "Debug"/> <appender-ref ref= "Myfil" E "/> </category> <!--root Logger settings--> <root> <!--priority setting, if set to "info", you cannot output debug-level logs--> <priority Valu
        e= "Debug"/> <!--<priority value= "info"/>--> <!--<priority value= "Warn"/>--> <!--<priority value= "error"/>--> <!--<priority value= "Fatal"/>--> <!--add just appender--> <appender-ref ref= "MyConsole"/> <appender-ref "ref=" MyFile/>
Gt </log4j:configuration>

Configuration file for console output log (replication can be used directly)

<?xml version= "1.0"  encoding= "UTF-8"?>
<! DOCTYPE log4j:configuration SYSTEM "Log4j.dtd" >
<log4j:configuration>
    <appender name= " MyConsole "class=" Org.apache.log4j.ConsoleAppender ">
        <layout class=" Org.apache.log4j.PatternLayout " >
            <param name= "Conversionpattern"
                   value= "%-d{yyyy-mm-dd hh:mm:ss,sss} [%c]-[%p]%m%n"/>
        </ layout>
    </appender>
    <root>
        <priority value= "Debug"/>
        <appender-ref ref = "MyConsole"/>
    </root>
</log4j:configuration>

Detailed configuration file, you can refer to: http://zengxiantao.iteye.com/blog/1881700 application Call

Class name. class
Logger Logger = Loggerfactory.getlogger (program.class);
Output string
logger.debug ("This is a debug msg");
Placeholder
Logger.debug ("Hi,welcome {},today is {}", "admin", "Sunday");
use of slf4j binding Logback pom.xml Add Dependencies

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.