Java日志体系
问题:spring 框架使用的JCL日志体系,如果应用想要使用log4j2,就无法避免要有两个日志输出文件?
析:slf4j提供将JCL日志转换为log4j2的日志门面,桥接器,转换器等。具体看下面代码。
spring框架日志体系
Spring 4.0版本使用的日志体系是JUL
示例说明
maven应用
pom文件
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
srping配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="slf4jOver" class="cn.ling.logs.Slf4jOverTest"/>
</beans>
测试类
public class Slf4jOverTest {
public static Log log = LogFactory.getLog(Slf4jOverTest.class);
public static void main(String[] args) {
ApplicationContext act =new ClassPathXmlApplicationContext("spring.xml");
act.getBean("slf4jOver");
log.debug("Debug info.");
log.info("Info info");
log.warn("Warn info");
log.error("Error info");
log.fatal("Fatal info");
}
}
输出结果
注意:这里省略了common-longging 配置文件 和log4j配置文件
JCL通过SLF4J转为log4j2日志输出
pom.xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<!--slf4j日志接口-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<!--将jcl替换为slf4j-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.25</version>
</dependency>
<!--slf4j log4j桥接器-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.7</version>
</dependency>
<!--log4j2-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>com.lmax</groupId>
<artifactId>disruptor</artifactId>
<version>3.3.11</version>
</dependency>
测试类
public class Slf4jOverTest {
public static Log log = LogFactory.getLog(Slf4jOverTest.class);
public static void main(String[] args) {
ApplicationContext act =new ClassPathXmlApplicationContext("spring.xml");
act.getBean("slf4jOver");
log.debug("Debug info.");
log.info("Info info");
log.warn("Warn info");
log.error("Error info");
log.fatal("Fatal info");
}
}
输出结果
ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.
上面报错原因是缺少log4j2.xml 具体配置文件,等后面写log4j2的笔记时在解释。
总结
SLF4j非常强大,不仅仅如上述例子中可以将框架中JCL日志转换为Log4j2 日志输出。也提供将其他日志转换输出的。具体方式和上述大差不差。