拓展阅读
Log4j2 系统学习
Logback 系统学习
Slf4j
Slf4j-02-slf4j 与 logback 整合
SLF4j MDC-日志添加唯一标识
分布式链路追踪-05-mdc 等信息如何跨线程? Log4j2 与 logback 的实现方式
日志开源组件(一)java 注解结合 spring aop 实现自动输出日志
日志开源组件(二)注解结合 spring aop 实现日志traceId唯一标识
日志开源组件(三)java 注解结合 spring aop 自动输出日志新增拦截器与过滤器
日志开源组件(四)如何动态修改 spring aop 切面信息?让自动日志输出框架更好用
日志开源组件(五)如何将 dubbo filter 拦截器原理运用到日志拦截器中?
日志开源组件(六)Adaptive Sampling 自适应采样
slf4j
Java的简单日志Facade (SLF4J)充当各种日志框架的简单Facade或抽象 (e.g. java.util.logging, logback, log4j)
允许最终用户在部署时插入所需的日志框架。
slf4j
log4j2
Apache Log4j 2是Log4j的升级版,在其前身Log4j 1.x的基础上提供了重大改进。
并提供了Logback中可用的许多改进,同时修复了Logback架构中的一些固有问题。
log4j2
只需使用log4j2而不是log4j和logback,原因如下。
-
Log4j 1。x和Logback将在重新配置时丢失事件。Log4j 2则不会。
-
在多线程场景下,异步logger具有10倍高的吞吐量和
延迟比Log4j 1低几个数量级。x和Logback。
- Log4jX有已知的死锁问题。其中许多在Logback中是固定的,但是
许多Logback类仍然需要相当高级别的同步。
- others…
Hello world
- pom.xml
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.6.1</version>
</dependency>
</dependencies>
- App.java
// Import log4j classes.
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
public class App {
static final Logger logger = LogManager.getLogger(App.class);
public static void main(String[] args) {
logger.trace("Entering application.");
Bar bar = new Bar();
if (!bar.doIt()) {
logger.error("Didn't do it.");
}
logger.trace("Exiting application.");
}
}
- Bar.java
public class Bar {
static final Logger logger = LogManager.getLogger(Bar.class.getName());
public boolean doIt() {
logger.entry();
logger.error("Did it again!");
return logger.exit(false);
}
}
- result
ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.
11:11:34.539 [main] ERROR com.ryo.logger.Bar - Did it again!
11:11:34.540 [main] ERROR com.ryo.logger.App - Didn't do it.
Process finished with exit code 0
- add log4j2.xml as following into classpath
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="trace">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
- and the result is:
11:22:58.433 [main] TRACE com.ryo.logger.App - Entering application.
11:22:58.437 [main] TRACE com.ryo.logger.Bar - entry
11:22:58.438 [main] ERROR com.ryo.logger.Bar - Did it again!
11:22:58.438 [main] TRACE com.ryo.logger.Bar - exit with(false)
11:22:58.438 [main] ERROR com.ryo.logger.App - Didn't do it.
11:22:58.438 [main] TRACE com.ryo.logger.App - Exiting application.
Process finished with exit code 0