1、先引入相关的jar包依赖
只引入下面的两个也可以,源代码如下:
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<!-- For log4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
2、编写log4j配置文件log4j.properties
代码如下:
### \u8bbe\u7f6e###
log4j.rootLogger = debug,D,E
### \u8f93\u51fa\u4fe1\u606f\u5230\u63a7\u5236\u62ac ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
### \u8f93\u51faDEBUG \u7ea7\u522b\u4ee5\u4e0a\u7684\u65e5\u5fd7\u5230=E://logs/error.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = F:/logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = INFO
log4j.appender.D.ImmediateFlush = true
log4j.appender.D.DatePattern='.'yyyy-MM-dd
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
### \u8f93\u51faERROR \u7ea7\u522b\u4ee5\u4e0a\u7684\u65e5\u5fd7\u5230=E://logs/error.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =F:/logs/error.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.ImmediateFlush = true
log4j.appender.E.DatePattern='.'yyyy-MM-dd
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
3、在程序中的使用
在控制器类中先定义 log,在每个方法中使用它。
代码如下:
private static Logger log = LogManager.getLogger(SysUserController.class);
public AjaxResult addUser(HttpServletRequest request,HttpServletResponse response,SysUserDto userDto){
try{
SysUser user = userDto.convertUser();
user.setId(GenerateID.getIdByUUID());
userService.addUser(user);
}catch(Exception e){
AjaxResult ajaxResult = AjaxResult.error();
e.printStackTrace();
log.error("添加用户:", e); //这一句就是生成错误日志信息
return ajaxResult;
}
return AjaxResult.success();
}
最后在 定义的日志文件输出路径下可以看到日志,比如上面配置文件中我定义的是 F:/logs/log.log F:/logs/error.log