slf4j和log4j结合使用步骤
使用slf4j的优点:
提供带参数的日志输出方法(SLF4J 1.7及以后版本)。
pom中只需引入slf4j-log4j12,然后maven会引入它所依赖的其它JAR包。
slf4j和log4j结合使用步骤:
1.在pom文件中添加代码(非maven项目自行下载jar包):
<dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.2</version> </dependency>
2.添加log4j配置文件log4j.properties:
# DEBUG,INFO,WARN,ERROR,FATAL
LOG_LEVEL=INFO
log4j.rootLogger=${LOG_LEVEL},CONSOLE,FILE
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Encoding=utf-8
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
#log4j.appender.CONSOLE.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss} %C{8}@(%F:%L):%m%n
log4j.appender.CONSOLE.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss} %C{1}@(%F:%L):%m%n
log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender
log4j.appender.FILE.File=${catalina.base}/logs/workorder.log
log4j.appender.FILE.Encoding=utf-8
log4j.appender.FILE.DatePattern='.'yyyy-MM-dd
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
#log4j.appender.FILE.layout=org.apache.log4j.HTMLLayout
log4j.appender.FILE.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH\:mm\:ss} %C{8}@(%F\:%L)\:%m%n
3.在web.xml中配置log4j:
<!-- 配置log4j配置文件路径 --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:conf/log4j.properties</param-value> </context-param> <!-- 60s 检测日志配置 文件变化 --> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>60000</param-value> </context-param> <!-- 配置Log4j监听器 --> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener>
4.在代码中打印日志:
private Logger logger = LoggerFactory.getLogger(TaskJob.class);
logger.info("带参日志测试:{}", "参数111");
日志输出:
[INFO ] 2017-03-14 17:20:00 TaskJob@(TaskJob.java:47):带参日志测试:参数111