1.新建module,jcl-demo
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>log-study</artifactId>
<groupId>com.lxcourse</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>jcl-demo</artifactId>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
2.JCLDemo.java默认使用JUL输出日志
package com.lxcourse.jcl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
public class JCLDemo {
@Test
public void testQuick(){
Log log = LogFactory.getLog(JCLDemo.class);
log.info("hello jcl");
}
}
输出结果:
五月 29, 2020 8:22:36 上午 com.lxcourse.jcl.JCLDemo testQuick
信息: hello jcl
3.pom.xml中添加log4j的依赖
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
4.添加log4j.properties
log4j.rootLogger=trace,console
# 指定控制台日志输出的appender
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.conversionPattern = [%-5p] %r %C %M %d{yyyy-MM-dd HH:mm:ss} %m%n
5.执行JCLDemo.testQuick()方法,查看输出
[INFO ] 0 com.lxcourse.jcl.JCLDemo testQuick 2020-05-29 08:29:57 hello jcl
6.JCL原理
- 通过LogFactory动态加载Log实现类
- 日志门面支持的日志实现数组
private static final String[] classesToDiscover = {
LOGGING_IMPL_LOG4J_LOGGER,
"org.apache.commons.logging.impl.Jdk14Logger",
"org.apache.commons.logging.impl.Jdk13LumberjackLogger",
"org.apache.commons.logging.impl.SimpleLog"
};
- 获取具体的日志实现
for(int i=0; i<classesToDiscover.length && result == null; ++i) {
result = createLogFromClass(classesToDiscover[i], logCategory, true);
}