idea+maven配置log4j详解

经过上一篇的讲解,知道了实现log4j打印日志依赖的jar包共3个,在pom.xml中加入相关依赖:

       <!-- 添加log4j日志相关jar包:共3个jar-->
        <!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</version>
            <scope>test</scope>
        </dependency>

第二步,在项目的 src/test/resource目录下新建log4j.properties文件,文件内容为: 

### set log levels ###
log4j.rootLogger = debug,stdout,R 

### console appender###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.Threshold = Info
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = %d [%t] %p [%c] - %m%n

### output to files ###
log4j.appender.R = org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.File = logs/log.txt
log4j.appender.R.Append = true
log4j.appender.R.Threshold = Info 
log4j.appender.R.layout = org.apache.log4j.PatternLayout
#log4j.appender.R.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}-[%p]%m%n
log4j.appender.R.layout.ConversionPattern = %d [%t] %p [%c] - %m%n

第三步,编写测试代码

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Log4jTest {
    public static void main(String[] args) {
        Logger LOG = LoggerFactory.getLogger(Log4jTest.class);
        LOG.info("开始记录日志...");
        LOG.info("循环打印0到10之间的整数");
        for(int i=0;i<10;i++) {
            System.out.println(i);
        }
        LOG.info("结束日志!");
    }
}

执行结果:

2018-11-30 12:54:53,071 [main] INFO [Log4jTest] - 开始记录日志...
2018-11-30 12:54:53,071 [main] INFO [Log4jTest] - 循环打印0到10之间的整数
0
1
2
3
4
5
6
7
8
9
2018-11-30 12:54:53,071 [main] INFO [Log4jTest] - 结束日志!

Process finished with exit code 0

第四步,在项目的相应目录下面查看生成的log文件,测试代码log日志所在路径为 /logs/log.txt

 

posted @ 2018-11-30 12:58  那心之所向  阅读(7473)  评论(0编辑  收藏  举报