Java SLF4J

Introduction

Simple Logging Facade for Java (SLF4J)

The Simple Logging Facade for Java (SLF4J) serves as a simple facade or abstraction for various logging frameworks (e.g. java.util.logging, logback, log4j) allowing the end user to plug in the desired logging framework at deployment time.


Configuation

pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<properties>
<sl4j.version>2.11.1</sl4j.version>
</properties>

<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${sl4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${sl4j.version}</version>
</dependency>

log4j2.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="ERROR">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Logger name="com.anda.engine" level="DEBUG" additivity="false">
<AppenderRef ref="Console"/>
</Logger>
<Root level="WARM">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>

注:如果不添加additivity=”false”属性,输出重复log

Enable AsyncLogger

  1. JVM启动参数(boot.ini)加上“-DLog4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector”

  2. classpath中添加文件“log4j2.component.properties”,文件增加以下内容:“Log4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector”

  3. 手工指定部分Logger采用异步方式log4j2.xml配置文件中使用AsyncRoot/AsyncLogger替代Root/Logger


Usage

1
val logger = LogManager.getLogger()
1
-Dlog4j.configurationFile=log4j2-dev.xml

Reference

https://www.slf4j.org/manual.html