slf4j、log4j2及logback使用

1、问题来源

之前看过关于slf4j、log4j2及logback的介绍,slf4j是门面,log4j2及logback是具体实现,仅使用slf4j门面是无法输出日志的。

本文采用jdk11,测试代码Slf4jTest.java如下:

import lombok.extern.slf4j.Slf4j;
@Slf4j
public class Slf4jTest {
    public static void main(String[] args) {
        log.info("info");
        log.debug("debug");
        log.error("error");
        log.warn("warn");
    }
}

@Slf4j需要<dependency>依赖如下:

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.24</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>2.0.0</version>
</dependency>

运行程序,不出意外,程序报错SLF4J: No SLF4J providers were found.。原因为代码只有slf4j门面,没有相关实现。

slf4j、log4j2及logback使用

2、slf4j与log4j2使用

(1)在maven依赖中引入slf4j-log4j12、及log4j-core包,如下图

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>2.0.0</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.18.0</version>
</dependency>

运行代码,之前的错误消失,取而代之的是log4j:WARN No appenders could be found for logger (binghe.concurrent.Slf4jTest).错误,如下图。原因为log4j2需要配置文件。

slf4j、log4j2及logback使用

(2)在项目resources目录下新建log4j.properties文件,代码如下

# Set root logger level to DEBUG and its only appender to console.
log4j.rootLogger=DEBUG, console
# console is set to be a ConsoleAppender.
log4j.appender.console=org.apache.log4j.ConsoleAppender
# console uses PatternLayout.
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold = DEBUG
log4j.appender.console.layout.ConversionPattern=%-4r [%t]  %-5p %c %x - %m%n

运行代码,程序正常输出:

0    [main]  INFO  binghe.concurrent.Slf4jTest  - info
1    [main]  DEBUG binghe.concurrent.Slf4jTest  - debug
2    [main]  ERROR binghe.concurrent.Slf4jTest  - error
2    [main]  WARN  binghe.concurrent.Slf4jTest  - warn

3、slf4j与logback使用

删除第2节中maven依赖引入的slf4j-log4j12、及log4j-core包。

(1)在maven依赖中引入logback-classic、及logback-core

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

(2)在项目resources目录下新建logback.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %msg%n</pattern>
        </encoder>
    </appender>
    <root level="DEBUG">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>

运行代码,程序正常输出:

2022-10-02 21:13:37.174 INFO  [main] info
2022-10-02 21:13:37.181 DEBUG [main] debug
2022-10-02 21:13:37.181 ERROR [main] error
2022-10-02 21:13:37.181 WARN  [main] warn

发表回复