概述
slf4j 不是具体的日志解决方案,它只服务于各种各样的日志系统。按照官方的说法,slf4j 是一个用于日志系统的简单 Facade,允许最终用户在部署其应用时使用其所希望的日志系统。
这篇文章将用 5 分钟讲解 slf4j 和 log4j 搭配使用的步骤和要点。
Maven 配置
<properties>
<!-- Application settings -->
<slf4j.version>1.7.10</slf4j.version>
<log4j.version>1.2.17</log4j.version>
</properties>
<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
</dependencies>
配置文件
在工程 resources 目录下创建 log4j 配置文件:log4j.properties
# Define some default values that can be overridden by system properties
linden.root.logger=INFO,console
linden.log.dir=/home/work/logs/linden
linden.log.file=linden.log
# Define the root logger to the system property "linden.root.logger".
log4j.rootLogger=${linden.root.logger}
# Logging Threshold
log4j.threshhold=ALL
#
# Daily Rolling File Appender
#
log4j.appender.DRFA=org.apache.log4j.DailyRollingFileAppender
log4j.appender.DRFA.File=${linden.log.dir}/${linden.log.file}
log4j.appender.DRFA.DatePattern=.yyyy-MM-dd
log4j.appender.DRFA.layout=org.apache.log4j.PatternLayout
log4j.appender.DRFA.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
#
# console
# Add "console" to rootlogger above if you want to use this
#
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.target=System.err
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
# Custom Logging levels
log4j.logger.org.springframework.security=ERROR
log4j.logger.org.apache.hadoop=INFO
log4j.logger.org.apache=WARN
log4j.logger.org.dbunit=WARN
log4j.logger.org.springframework=WARN
上述配置中,linden 是我的项目名字,你可以根据你的具体需求做替换。
代码实现
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Test {
private static final Logger logger = LoggerFactory.getLogger(Test.class);
public static void main(String[] args) {
logger.info("hello {}", "world");
}
}