一、pom引入的包
<!-- log4-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.10</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.10</version>
</dependency>
二、log4j.properties 代码如下:
### Application log config
log4j.rootLogger=info,consoleInfoLog,fileErrorLog
### direct log messages to stdout
log4j.appender.consoleInfoLog=org.apache.log4j.ConsoleAppender
log4j.appender.consoleInfoLog.Target=System.out
log4j.appender.consoleInfoLog.layout=org.apache.log4j.PatternLayout
log4j.appender.consoleInfoLog.layout.ConversionPattern=[%d{yyyy-MM-dd HH:mm:ss.SSS}] [%t] [%p] [%c] - %m%n
### log messages to file
log4j.appender.fileErrorLog=org.apache.log4j.DailyRollingFileAppender
log4j.appender.fileErrorLog.Append=true
log4j.appender.fileErrorLog.Encoding=UTF-8
log4j.appender.fileErrorLog.File=../logs/log-error
log4j.appender.fileErrorLog.DatePattern='_'yyyy-MM-dd'.log'
log4j.appender.fileErrorLog.layout=org.apache.log4j.PatternLayout
log4j.appender.fileErrorLog.layout.ConversionPattern=[%d{yyyy-MM-dd HH:mm:ss.SSS}] [%t] [%p] [%c] - %m%n
### set log levels
log4j.logger.org.springframework=WARN
log4j.logger.org.hibernate=WARN
注意,这个文件一般都放到src/main/resources下面,但是有时候读不到,如果读不到就放到WEB-INF下
三、web.xml添加如下代码
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.properties</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
四、java代码里面如何使用:
头部导入:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
全局变量:
private static final Logger logger = LoggerFactory.getLogger(WxPaymentController.class);
方法内部使用:
logger.info("code=测试日志打印===" + code);