Detailed explanation of slf4j log4j logback relationship and related usage

 Reprinted from: https://www.cnblogs.com/Sinte-Beuve/p/5758971.html

Detailed explanation of slf4j log4j logback relationship and related usage

I have been writing java for a while, and I have always used slf4j log4j to output logs. But I always have the attitude of "use it", copy and paste the configuration file and start coding, so I looked at the log library in detail during this time.

slf4j log4j logback relationship

What is The Simple Logging Facade for Java?

Generally speaking, slf4j is a series of log interfaces, and log4j logback is a log framework that is specifically implemented. Next, let's take a detailed look at their relationship with the official documentation.

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

This paragraph of the official document has clearly described the relationship between the three. slf4j is translated as a simple log facade, which is an abstraction of the log framework. And log4j and logback are several of the many logging frameworks.

Here are a few simple lines of code written to verify it.

public class Program {
    publicstaticvoidmain(String[] args) {
        Logger logger = LoggerFactory.getLogger(Program.class);
        logger.info("hello world");
    }
}

As can be seen from the running results, since no specific logger implementation is given, the log cannot be output to the console. That is to say, in the specific development, we need to bind a logging framework to use slf4j normally.

What about log4j and logback?

And log4j and logback are two popular logging frameworks. But the two are different.

  • log4j is an open source logging component implemented by apache. (Wrapped implementations)
  • Logback is also designed by the author of log4j and has better features to replace a logging framework of log4j. is a native implementation of slf4j. (Native implementations)

enter image description here
The above figure shows the calling relationship of the application to the logging framework. The application calls the slf4j api, and the output of the log is finally realized by the underlying logging framework. This picture also shows the difference between log4j and logback.

Description of logback in official documentation

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 zero memory and computational overhead.

It can be seen that logback directly implements the interface of slf4j, which does not consume memory and computational overhead. And log4j is not a native implementation of slf4j, so slf4j api needs an adaptation layer when calling log4j.

Summarize:

  1. slf4j is a log facade of java, which implements some common APIs of the log framework. log4j and logback are specific log frameworks.
  2. They can be used alone or bundled with slf4j.
  • Use alone. Call the framework's own methods to output log information respectively.
  • Binding for use with slf4j. Call the api of slf4j to input log information, the specific use has nothing to do with the underlying log framework (the configuration file of the underlying framework is required)

Obviously here we do not recommend using the logging framework alone. Suppose log4j is already used in the project, and we load a class library at this time, and this class library depends on another logging framework. At this time, we need to maintain two log frameworks, which is a very troublesome thing. However, using slf4j is different. Since the API of the abstraction layer called by the application has nothing to do with the underlying logging framework, the logging framework can be changed arbitrarily.

Advantages of using slf4j to bind the logging system

  • A software engineering perspective. Abstraction, decoupling, and easy maintenance. You can refer to the above example.
  • Grammar design angle. slf4j has {} placeholders, and log4j needs to use "+" to concatenate strings, which is not conducive to reading and consumes heap memory.
  • For a detailed description, please refer to: http://www.importnew.com/7450.html

log4j and logback

As a log4j developer, you must be familiar with log4j, an open source logging framework of apache. Compared with log4j, logback is a little newer. It was designed and implemented by the author of log4j. The first version was launched in 2011. In terms of design and implementation, Logback has relatively many improvements over log4j. But there is almost no difference in the usage of the two. Here are the advantages of logback:

  • faster execution
  • adequate testing
  • logback-classic implements SLF4J very naturally
  • Rich extended documentation
  • You can use XML configuration files or Groovy
  • Automatically reload configuration files
  • Gracefully recover from I/O errors
  • Automatically purge old log archives
  • Automatically compress archive log files
  • For more advantages, please refer to the official documentation. Chinese version  English version

Above, from a performance point of view, you can migrate from log4j to logback as soon as possible.

The usage of slf4j binding log4j

Since log4j is still used a lot now, I will introduce his basic usage.

IDE related settings

Here we use IntelliJ IDEA2016.1 and maven.

  1. Add related dependencies in pom.xml.
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.21</version>
</dependency>

At this point, three jar packages will be automatically added.

configuration file

The normal operation of log4j requires a configuration file. The type of configuration file: 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 Internet use log4j.properties to configure (key-value pairs), I personally think that using xml configuration, the nodes are clearer, and there are code prompts under the idea, which can reduce the probability of configuration errors. I will not talk about the configuration file in detail below, but only mention a few key places.

  1. A root logger and an appender must be configured.
  2. 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>

    <!--若干个appender的定义-->
    <!--org.apache.log4j.ConsoleAppender 输出到控制台-->
    <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>

    <!--org.apache.log4j.DailyRollingFileAppender 每天产生一个日志文件-->
    <appender name="myFile" class="org.apache.log4j.DailyRollingFileAppender">
        <param name="File" value="output.log"/><!--文件位置-->
        <param name="Append" value="true"/><!--是否选择追加-->
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern"
                   value="%-d{yyyy-MM-dd HH:mm:ss,SSS} [%c]-[%p] %m%n"/>
        </layout>
    </appender>

    <!--org.apache.log4j.RollingFileAppender 滚动日志文件输出 文件大小到达一定尺寸时重新产生新的文件-->
    <!--<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="MaxBackupIndex" value="10" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%p (%c:%L)- %m%n" />
        </layout>
    </appender>-->

    <!--将各个包中的类日志输出到不同的日志文件中
        这样可以便于日志的分类。
        可以通过这个设置,把业务逻辑的日志添加到数据库。起到过滤的作用
    -->
    <!--这段配置的就是说把包名为“com.zjut.a1”且优先级为debug的日志通过myFile这个appender来处理。
    -->
    <category name="com.zjut.a1">
        <priority value="debug"/>
        <appender-ref ref="myFile"/>
    </category>


    <!-- 根logger的设置-->
    <root>
        <!--优先级设置,假设设置为“info”,则无法输出debug级别的日志-->
        <priority value="debug"/>
        <!--<priority value="info"/>-->
        <!--<priority value="warn"/>-->
        <!--<priority value="error"/>-->
        <!--<priority value="fatal"/>-->

        <!--添加刚才设置的appender-->
        <appender-ref ref="myConsole"/>
        <appender-ref ref="myFile"/>
    </root>
</log4j:configuration>

Configuration file for console output log (copy 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>

For a detailed explanation of the configuration file, you can refer to: http://zengxiantao.iteye.com/blog/1881700

application call

 // 类名.class
Logger logger = LoggerFactory.getLogger(Program.class);
// 输出字符串
logger.debug("this is a debug msg");
// 占位符
logger.debug("hi,welcome {},today is {}","admin","Sunday");

The usage of slf4j binding logback

pom.xml add dependencies

<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.1.7</version>
</dependency>

Many online tutorials have been added. In fact, as long as this one is added, other dependent jars will be downloaded.

configuration file

The configuration file is almost the same as log4j, as follows. Just select the desired appender.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>


    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <!-- encoders are assigned the type
             ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
        <encoder>
            <pattern>%-4relative [%thread] %-5level %logger{35} - %msg %n</pattern>
        </encoder>
    </appender>

    <!-- Insert the current time formatted as "yyyyMMdd'T'HHmmss" under
         the key "bySecond" into the logger context. This value will be
         available to all subsequent configuration elements. -->
    <timestamp key="bySecond" datePattern="yyyyMMdd'T'HHmmss"/>

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>testFile-${bySecond}.log</file>
        <append>true</append>
        <!-- encoders are assigned the type
             ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
        <encoder>
            <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="DAYFILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>logFile.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- daily rollover -->
            <fileNamePattern>logFile.%d{yyyy-MM-dd}.log</fileNamePattern>

            <!-- keep 30 days' worth of history capped at 3GB total size -->
            <maxHistory>30</maxHistory>
            <totalSizeCap>3GB</totalSizeCap>

        </rollingPolicy>

        <encoder>
            <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="debug">
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="DAYFILE"/>
        <appender-ref ref="FILE"/>
    </root>
</configuration>

For detailed configuration files, you can refer to http://logback.qos.ch/manual/index.html.
Although it is in English, it is written very clearly.

program call

The same is the api of slf4j, the code is the same.

 // 类名.class
Logger logger = LoggerFactory.getLogger(Program.class);
// 输出字符串
logger.debug("this is a debug msg");
// 占位符
logger.debug("hi,welcome {},today is {}","admin","Sunday");

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326142818&siteId=291194637