lf4j是Java的简单日志门面API,很多日志实现都可以与之集成,如JDK logging (java.util.logging), log4j和logback。优点是代码里不会有具体的日志实现类,减少侵入。
与log4j相比,logback具有一些优势,如更好的性能、更少的内存使用、自动重加载配置文件以及过滤功能等。
下面简要介绍下logback的使用:
1. 在pom.xml文件中添加依赖:
2. 在类路径下新建logback.xml或logback-test.xml(优先级高)文件:
3. 测试类:
输出:
11:50:16.266 [main] INFO c.j.l.a.Reconciliation - Hello from reconciliate
11:50:16.270 [main] DEBUG c.j.l.a.Reconciliation - My name is conciliate
11:50:16.271 [main] INFO c.j.l.b.Corruption - Hello from corrupt.
11:50:16.271 [main] INFO c.j.l.b.Corruption - Hello from corrupt.
所有logger的始祖是ROOT,默认会继承ROOT的配置,因此Corruption中的日志会打印两次。
解决:logger的additivity属性设置为false
与log4j相比,logback具有一些优势,如更好的性能、更少的内存使用、自动重加载配置文件以及过滤功能等。
下面简要介绍下logback的使用:
1. 在pom.xml文件中添加依赖:
- <properties>
- <logback.version>1.0.11</logback.version>
- <slf4j.api.version>1.7.5</slf4j.api.version>
- </properties>
- <dependencies>
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- <version>${slf4j.api.version}</version>
- </dependency>
- <dependency>
- <groupId>ch.qos.logback</groupId>
- <artifactId>logback-classic</artifactId>
- <version>${logback.version}</version>
- </dependency>
- <dependency>
- <groupId>ch.qos.logback</groupId>
- <artifactId>logback-core</artifactId>
- <version>${logback.version}</version>
- </dependency>
- </dependencies>
2. 在类路径下新建logback.xml或logback-test.xml(优先级高)文件:
- <?xml version="1.0" encoding="UTF-8"?>
- <configuration>
- <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
- <!-- encoder的默认实现类是ch.qos.logback.classic.encoder.PatternLayoutEncoder -->
- <encoder>
- <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{5} - %msg%n</pattern>
- </encoder>
- </appender>
- <!-- name值可以是包名或具体的类名:该包(包括子包)下的类或该类将采用此logger -->
- <logger name="com.john.logging.b" level="INFO">
- <appender-ref ref="STDOUT" />
- </logger>
- <!-- root的默认level是DEBUG -->
- <root level="DEBUG">
- <appender-ref ref="STDOUT" />
- </root>
- </configuration>
3. 测试类:
- package com.john.logging.a;
- public class Reconciliation {
- private static final Logger log = LoggerFactory.getLogger(Reconciliation.class);
- public void reconciliate() {
- String name = "conciliate";
- log.info("Hello from reconciliate");
- log.debug("My name is {}", name);
- }
- }
- package com.john.logging.b;
- public class Corruption {
- // logger名称为类的全限定名
- private static final Logger log = LoggerFactory.getLogger(Corruption.class);
- public void corrupt() {
- String name = "allegation";
- log.info("Hello from corrupt.");
- log.debug("My name is {}", name);
- }
- }
输出:
11:50:16.266 [main] INFO c.j.l.a.Reconciliation - Hello from reconciliate
11:50:16.270 [main] DEBUG c.j.l.a.Reconciliation - My name is conciliate
11:50:16.271 [main] INFO c.j.l.b.Corruption - Hello from corrupt.
11:50:16.271 [main] INFO c.j.l.b.Corruption - Hello from corrupt.
所有logger的始祖是ROOT,默认会继承ROOT的配置,因此Corruption中的日志会打印两次。
解决:logger的additivity属性设置为false
- <logger name="com.john.logging.b" level="INFO" additivity="false">