Java logging framework --Slf4j use

First, the significance of the facade of the log

When our systems become more complex, we log prone to confusion. With the operation of the system development, you may update a different logging framework, resulting in the presence of different log rely on the current system, make it difficult to unified management and control, even if we force all modules use the same logging framework, the system also difficult to avoid the use of other third-party framework of other similar spring, mybatis etc., they rely on us specify different logging framework, but also on their own logging system has inconsistencies, confusion still out log system. . .

Common Log facade: JCL, SLF4J

Common logging implementation: JUL, log4j, logback, log4j2

Two, Slf4j use ( http://www.slf4j.org/ )

Simply log facade (Simple Logging Facade For Java): Slf4j mainly in order to provide a set of standard Java logging access, standardized API framework, its main significance is to provide an interface specific implementation may be referred to other logging frameworks such as log4j and logback Wait. Of course slf4j himself provides the ability to achieve relatively simple, but rarely used. For general java project, select the log framework slf4j-api as a facade, coupled with the specific implementation framework (log4j, logback etc.), using an intermediate bridge to complete the bridge.

slf4j is currently the world face the most popular log facade. Now the project, basically using slf4j as our log system.

Slf4j log facade mainly provides two functions:

     1. Binding logging framework;

slf4j supports various logging framework. slf4j release comes a few jar files called "slf4j binding", each binding corresponds to a framework supported.

Use slf4j logs binding process:

(1) was added depends slf4j-api

(2) the use of API slf4j unified logging project

(3) specific binding logging implementation framework

   Binding has been achieved slf4j logging framework, added directly dependent on the corresponding

   Binding slf4j logging framework is not achieved, the first add log adapters, add-dependent implementation class

(4) slf4j and only achieved a log of the binding frame (default occurs if a plurality of first dependent log implementation)

To switch logging framework, you can simply replace slf4j bound on the classpath. For example, to switch from log4j java.util.logging, simply replace slf4j-jdk14-1.7.28.jar as slf4j-log4j12-1.7.28.jar.

SLF4J not dependent on any particular class loader. In fact, each SLF4J binding at compile time are  hard-wired , to use one and only one specific logging framework. For example, slf4j-log4j12-1.7.28.jar binding bindings for use log4j at compile time. In the code, in addition than the API-1.7.28.jar-SLF4J , you only need to choose one and only one bound to the appropriate class path drag position. Do not place multiple bindings on the class path. This is a graphical illustration of the general idea.

2. The logging framework bridge;

Typically, some of the components you rely on rely on outside slf4j logging API. You can also assume that these components do not switch to slf4j in the near future. To address this situation, slf4j bridge comes with several modules that will log4j, JCL and java.util.logging API call redirection, as if they were the same for slf4j API.

The solution is to bridge the remaining issues in the project log, when present in the system before logging API, you can switch to slf4j achieved by bridging

1. Before rely first remove the old logging framework

2. Add the bridging component provided slf4j

3. Add slf4j for the project realization 

Attention to the problem:

1.jcl-over-slf4j.jarslf4j-jcl.jar不能同时部署。前一个jar文件将导致jcl将日志系统的选择委托给slf4j,后一个jar文件将导致slf4j将日志系统的选择委托给jcl,从而导致无限循环。

2.log4j-over-slf4j.jarslf4j-log4j12.jar不能同时出现

3.jul-to-slf4j.jarslf4j-jdk14.jar不能同时出现

4.所有的桥接都只对Logger日志记录器对象有效,如果程序中调用了内部的配置类或者是Appender,Filter等对象,将无法产生效果。

三、Slf4j入门

日志框架的绑定:

1.添加依赖:

slf4j绑定内置的日志实现框架

 <!--        slf4j日志门面-->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.26</version>
    </dependency>
<!--        slf4j内置的简单实现-->
    <dependency>
         <groupId>org.slf4j</groupId>
         <artifactId>slf4j-simple</artifactId>
         <version>1.7.21</version>
    </dependency>

slf4j绑定logback日志实现框架

<!--        slf4j日志门面-->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.26</version>
    </dependency>

<!--        logback日志实现-->
    <dependency>
          <groupId>ch.qos.logback</groupId>
          <artifactId>logback-classic</artifactId>
          <version>1.2.3</version>
    </dependency>

 nop日志开关:

<!--        slf4j日志门面-->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.26</version>
    </dependency>

<!--        nop日志开关-->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-nop</artifactId>
        <version>1.7.25</version>
    </dependency>

slf4j绑定log4j日志实现框架 


<!--        slf4j日志门面-->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.26</version>
    </dependency>

<!--    绑定 log4j日志实现,需要导入适配器-->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.29</version>
    </dependency>

    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>

绑定 log4j日志实现,不仅需要导入适配器,还需要导入配置文件log4j.properties:

#配置根  Loggers控制日志的输出级别与日志是否输出
log4j.rootLogger=trace,console

#自定义logger对象设置
log4j.logger.LoggerDemo = info,file

#配置输出到控制台  Appenders是指定日志的输出方式
log4j.appender.console=org.apache.log4j.ConsoleAppender
#指定输出控制台
log4j.appender.console.Target = System.out
#指定布局,输出日志的格式
log4j.appender.console.layout=org.apache.log4j.PatternLayout
#指定布局的参数
log4j.appender.console.layout.ConversionPattern=[%-10p] %r %l %d{yyyy-MM-dd HH:mm:ss.SSS} %m%n


#配置输出到控制台  Appenders是指定日志的输出方式
log4j.appender.file=org.apache.log4j.FileAppender
#指定布局,输出日志的格式
log4j.appender.file.layout=org.apache.log4j.PatternLayout
#指定布局的参数
log4j.appender.file.layout.ConversionPattern=[%-10p] %r %l %d{yyyy-MM-dd HH:mm:ss.SSS} %m%n
#指定日志文件保存路径
log4j.appender.file.file = /logs/log4j.log
#指定日志文件字符集
log4j.appender.file.encoding = UTF-8

#配置输出到控制台  Appenders是指定日志的输出方式
log4j.appender.rollingFile=org.apache.log4j.RollingFileAppender
#指定布局,输出日志的格式
log4j.appender.rollingFile.layout=org.apache.log4j.PatternLayout
#指定布局的参数
log4j.appender.rollingFile.layout.ConversionPattern=[%-10p] %r %l %d{yyyy-MM-dd HH:mm:ss.SSS} %m%n
#指定日志文件保存路径
log4j.appender.rollingFile.file = /logs/log4j.log
#指定日志文件字符集
log4j.appender.rollingFile.encoding = UTF-8
#指定日志文件内容的大小
log4j.appender.rollingFile.maxFileSize = 1MB
#指定日志文件的数量
log4j.appender.rollingFile.maxBackupIndex = 10

#配置输出到控制台  Appenders是指定日志的输出方式
log4j.appender.dailyRollingFile=org.apache.log4j.DailyRollingFileAppender
#指定布局,输出日志的格式
log4j.appender.dailyRollingFile.layout=org.apache.log4j.PatternLayout
#指定布局的参数
log4j.appender.dailyRollingFile.layout.ConversionPattern=[%-10p] %r %l %d{yyyy-MM-dd HH:mm:ss.SSS} %m%n
#指定日志文件保存路径
log4j.appender.dailyRollingFile.file = /logs/log4j.log
#指定日志文件字符集
log4j.appender.dailyRollingFile.encoding = UTF-8
#指定日志输出规则
log4j.appender.dailyRollingFile.datePattern = '.'yyyy-MM-dd-HH-mm-ss


#mysql
log4j.appender.logDB=org.apache.log4j.jdbc.JDBCAppender
#指定布局,输出日志的格式
log4j.appender.logDB.layout=org.apache.log4j.PatternLayout

log4j.appender.logDB.Driver = com.mysql.jdbc.Driver
log4j.appender.logDB.URL = jdbc:mysql://localhost:3306/logs
log4j.appender.logDB.User = root
log4j.appender.logDB.Password = root
log4j.appender.logDB.Sql = INSERT INTO log(project_name,create_date,level,category,file_name,thread_name,line,all_category,message) values('itcast','%d{yyyy-MM-dd HH:mm:ss}','%p','%c','%F','%t','%L','%l','%m')

slf4j绑定jul日志实现框架 


  <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.5.6</version>
    </dependency>

<!--    绑定jul日志实现,需要导入适配器-->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-jdk14</artifactId>
        <version>1.5.6</version>
    </dependency>

2.测试Demo

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SLF4j {

    public static final Logger LOGGER = LoggerFactory.getLogger(SLF4j.class);

//        快速入门
    @Test
    public void test01() throws Exception{
//        日志输出
        LOGGER.error("error");
        LOGGER.warn("waring");
        LOGGER.info("info");
        LOGGER.debug("debug");
        LOGGER.trace("trace");

//        使用占位符输出日志消息
        String name = "itheima";
        Integer age = 14;
        LOGGER.info("用户:{},{}",name,age);

//        异常日志输出
        try {
            int i = 1/0;
        } catch (Exception e) {
            LOGGER.error("出现异常:",e);
        }
    }
}

3.测试结果:

slf4j绑定内置的日志实现框架的测试结果:

[main] ERROR SLF4j - error
[main] WARN SLF4j - waring
[main] INFO SLF4j - info
[main] INFO SLF4j - 用户:itheima,14
[main] ERROR SLF4j - 出现异常:
java.lang.ArithmeticException: / by zero
	at SLF4j.test01(SLF4j.java:26)
...

slf4j绑定logback日志实现框架的测试结果:

20:25:21.724 [main] ERROR SLF4j - error
20:25:21.739 [main] WARN SLF4j - waring
20:25:21.739 [main] INFO SLF4j - info
20:25:21.739 [main] DEBUG SLF4j - debug
20:25:21.739 [main] INFO SLF4j - 用户:itheima,14
20:25:21.742 [main] ERROR SLF4j - 出现异常:
java.lang.ArithmeticException: / by zero
	

 nop日志开关,打开日志开关的测试结果:

 日志开关打开了,关闭了日志打印的功能

F:\DevelopmentTools\Java\jdk1.8.0_152\bin\java.exe -ea -...

Process finished with exit code 0

slf4j绑定log4j日志实现框架的测试结果:

[ERROR     ] 0 SLF4j.test01(SLF4j.java:14) 2020-02-20 00:10:50.942 error
[WARN      ] 3 SLF4j.test01(SLF4j.java:15) 2020-02-20 00:10:50.945 waring
[INFO      ] 3 SLF4j.test01(SLF4j.java:16) 2020-02-20 00:10:50.945 info
[DEBUG     ] 3 SLF4j.test01(SLF4j.java:17) 2020-02-20 00:10:50.945 debug
[TRACE     ] 4 SLF4j.test01(SLF4j.java:18) 2020-02-20 00:10:50.946 trace
[INFO      ] 5 SLF4j.test01(SLF4j.java:23) 2020-02-20 00:10:50.947 用户:itheima,14
[ERROR     ] 5 SLF4j.test01(SLF4j.java:28) 2020-02-20 00:10:50.947 出现异常:
java.lang.ArithmeticException: / by zero

slf4j绑定jul日志实现框架的测试结果:

二月 20, 2020 12:31:55 下午 SLF4j test01
严重: error
二月 20, 2020 12:31:55 下午 SLF4j test01
警告: waring
二月 20, 2020 12:31:55 下午 SLF4j test01
信息: info
二月 20, 2020 12:31:55 下午 SLF4j test01
信息: 用户:itheima,14
二月 20, 2020 12:31:55 下午 SLF4j test01
严重: 出现异常:
java.lang.ArithmeticException: / by zero

日志框架的桥接:

1.添加依赖:

log4j的桥接器,替代log4.jar包以及适配器,让logback日志实现log4j日志

<!--        slf4j日志门面-->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.26</version>
    </dependency>
<!--        logback日志实现-->
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.2.3</version>
    </dependency>
<!--    配置log4j的桥接器-->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>log4j-over-slf4j</artifactId>
        <version>1.7.26</version>
    </dependency>

2.测试demo 

import org.apache.log4j.Logger;
import org.junit.Test;

public class Log4jTest {
//    定义 log4j 日志记录器
    public static final Logger LOGGER = Logger.getLogger(Log4jTest.class);

//    测试桥接器
    @Test
    public void test01() throws Exception{
        LOGGER.info("hello log4j");
    }

}

3.测试结果:

13:20:55.469 [main] INFO Log4jTest - hello log4j

 

发布了17 篇原创文章 · 获赞 11 · 访问量 7998

Guess you like

Origin blog.csdn.net/LOVE_Me__/article/details/104395184