1. 简介
SLF4J(Simple Logging Facade for Java) 是Java的一个简单日志门面,为Java日志访问提供了一套标准、规范的API框架。而具体日志的实现则可以根据这套接口去实现具体的日志框架,以便将来需要更换日志框架时,只替换实现框架即可。常见的具体实现有JUL、log4j、logback、log4j2等。
2. 操作
2.1 引入依赖
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.16</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.5.8</version>
</dependency>
2.2 配置日志实现
对于Logback,通常在类路径下(如src/main/resources目录)创建一个名为logback-config.xml配置文件,在其中定义日志记录级别、格式、输出目的地等。
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<!-- 工程名/项目名 -->
<contextName>project_name</contextName>
<!-- 把>=debug的日志输出到控制台 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%-4relative %date{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{35} - %msg %n</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<!-- 系统日志输出到文件,并设置滚动策略 -->
<appender name="INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>logs/info.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>logs/info.%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>30</maxHistory>
</rollingPolicy>
<encoder>
<pattern>%-4relative %date{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{35} - %msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>DENY</onMatch>
<onMismatch>ACCEPT</onMismatch>
</filter>
</appender>
<!-- 错误日志输出到文件,并设置滚动策略 -->
<appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>logs/error.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>logs/error.%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>30</maxHistory>
</rollingPolicy>
<encoder>
<pattern>%-4relative %date{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{35} - %msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 根日志级别控制,并引用所有appender -->
<root level="INFO">
<appender-ref ref="STDOUT"/>
<appender-ref ref="INFO_FILE"/>
<appender-ref ref="ERROR_FILE"/>
</root>
</configuration>
2.3 启用配置并使用
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.util.StatusPrinter2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.InputStream;
public class Main {
public static void main(String[] args){
// step1: 使用配置文件完成配置
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
try {
InputStream configStream = Main.class.getClassLoader().getResourceAsStream("logback-config.xml");
if (configStream == null) {
throw new RuntimeException("Could not find logback-config.xml");
}
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
context.reset();
configurator.doConfigure(configStream);
new StatusPrinter2().printInCaseOfErrorsOrWarnings(context);
} catch (JoranException je) {
throw new RuntimeException(je);
}
// step2: 进行日志记录
Logger log = LoggerFactory.getLogger(Main.class);
log.info("this is a logger!");
}
}
3. SLF4J的优势
- 解耦:SLF4J将应用程序和日志记录框架分离,从而编写独立于日志记录框架的应用程序;
- 灵活性:由于SLF4J提供了对各种日志框架的绑定与桥接,可以灵活地切换日志框架;
- 易用性:SLF4J的API设计简洁明了,易于学习和使用;