Log日志配置
- 方法一:视频学习
按照操作在maven项目的pom.xml中添加如下log4j依赖
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
且在同级工程目录中创建log4j.properties文件,设置如下格式
### 设置 ###
log4j.rootLogger = debug,stdout,D,E
### 输出信息到控制台 ###
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
### 输出DEBUG级别以上的日志 ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = /home/sheehan/Software/eclipse-workspace/second-maven/logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
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
### 输出ERROR级别以上的日志 ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File = /home/sheehan/Software/eclipse-workspace/second-maven/logs/error.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
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
然后在程序中写入
public class TestClass {
private Logger log = Logger.getLogger(TestClass.class); // 注意与方法二中声明的区别
@Test
public void method(){
log.info("message");
log.warn("!!!!!!!");
}
}
- 方法二:参考博文
添加如下依赖
<!--log4j-->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging-api</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.26</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.26</version>
</dependency>
然后在程序中写入
public class TestClass {
private org.slf4j.Logger log = LoggerFactory.getLogger(Log4jTest.class); //注意与方法一中声明的区别
@Test
public void method(){
log.info("message");
log.warn("!!!!!!!");
}
}
- Log4j打印异常堆栈信息到日志——参考博文
@Test
public void testError() {
String s = null;
try {
s.length();
} catch (Exception e) {
log.error(s, e);
//当然如果你懒得想提示信息的话,直接这样log.error("", e);
}
}