“Log4j 2 入门”的版本间的差异
		
		
		
		
		
		跳到导航
		跳到搜索
		
				
		
		
	
| Jihongchang(讨论 | 贡献) | Jihongchang(讨论 | 贡献)  | ||
| 第164行: | 第164行: | ||
| === 示例 使用 SLF4J 作为日志门面,Log4j 2 作为日志实现 === | === 示例 使用 SLF4J 作为日志门面,Log4j 2 作为日志实现 === | ||
| + | |||
| + | ==== pom.xml ==== | ||
| + | <syntaxhighlight lang="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"> | ||
| + |     <modelVersion>4.0.0</modelVersion> | ||
| + | |||
| + |     <groupId>io.github.jihch</groupId> | ||
| + |     <artifactId>log4j2-demo</artifactId> | ||
| + |     <version>1.0-SNAPSHOT</version> | ||
| + | |||
| + |     <properties> | ||
| + |         <maven.compiler.source>8</maven.compiler.source> | ||
| + |         <maven.compiler.target>8</maven.compiler.target> | ||
| + |     </properties> | ||
| + | |||
| + |     <dependencies> | ||
| + | |||
| + |         <!-- 使用 SLF4J 作为日志门面 --> | ||
| + |         <dependency> | ||
| + |             <groupId>org.slf4j</groupId> | ||
| + |             <artifactId>slf4j-api</artifactId> | ||
| + |             <version>1.7.26</version> | ||
| + |         </dependency> | ||
| + | |||
| + |         <!-- 使用 Log4j 2 的适配器进行绑定 --> | ||
| + |         <dependency> | ||
| + |             <groupId>org.apache.logging.log4j</groupId> | ||
| + |             <artifactId>log4j-slf4j-impl</artifactId> | ||
| + |             <version>2.9.1</version> | ||
| + |         </dependency> | ||
| + | |||
| + |         <!-- Log4j 2 的日志门面 --> | ||
| + |         <dependency> | ||
| + |             <groupId>org.apache.logging.log4j</groupId> | ||
| + |             <artifactId>log4j-api</artifactId> | ||
| + |             <version>2.11.1</version> | ||
| + |         </dependency> | ||
| + | |||
| + |         <!-- Log4j 2 的日志实现 --> | ||
| + |         <dependency> | ||
| + |             <groupId>org.apache.logging.log4j</groupId> | ||
| + |             <artifactId>log4j-core</artifactId> | ||
| + |             <version>2.11.1</version> | ||
| + |         </dependency> | ||
| + | |||
| + |         <!-- JUnit 单元测试 --> | ||
| + |         <dependency> | ||
| + |             <groupId>junit</groupId> | ||
| + |             <artifactId>junit</artifactId> | ||
| + |             <version>4.12</version> | ||
| + |         </dependency> | ||
| + | |||
| + |     </dependencies> | ||
| + | |||
| + | </project> | ||
| + | </syntaxhighlight> | ||
| + | |||
| + | ==== SLF4JTest.java ==== | ||
| + | <syntaxhighlight lang="java"> | ||
| + | import org.junit.Test; | ||
| + | import org.slf4j.Logger; | ||
| + | import org.slf4j.LoggerFactory; | ||
| + | |||
| + | public class SLF4JTest { | ||
| + | |||
| + |     public static final Logger LOGGER = LoggerFactory.getLogger(SLF4JTest.class); | ||
| + | |||
| + |     @Test | ||
| + |     public void test() { | ||
| + |         // 日志输出 | ||
| + |         LOGGER.error("error"); | ||
| + |         LOGGER.warn("warn"); | ||
| + |         LOGGER.info("info"); | ||
| + |         LOGGER.debug("debug"); | ||
| + |         LOGGER.trace("trace"); | ||
| + | |||
| + |     } | ||
| + | |||
| + | } | ||
| + | </syntaxhighlight><syntaxhighlight lang="console"> | ||
| + | 11:28:45.483 [main] [ERROR] io.github.jihch.SLF4JTest:14 --- error | ||
| + | 11:28:45.485 [main] [WARN ] io.github.jihch.SLF4JTest:15 --- warn | ||
| + | 11:28:45.485 [main] [INFO ] io.github.jihch.SLF4JTest:16 --- info | ||
| + | 11:28:45.485 [main] [DEBUG] io.github.jihch.SLF4JTest:17 --- debug | ||
| + | 11:28:45.485 [main] [TRACE] io.github.jihch.SLF4JTest:18 --- trace | ||
| + | </syntaxhighlight> | ||
2023年2月28日 (二) 03:30的最新版本
https://www.bilibili.com/video/BV1iJ411H74S?p=32
简介
Apache Log4j 2 是对 Log4j 的升级版,参考了 Logback 的一些优秀设计,并且修复了一些问题,因此带来了一些重大提升,主要有:
- 异常处理,在 Logback 中,Appender 中的异常不会被应用感知到,但是在 Log4j 2 中,提供了一些异常处理机制。
- 性能提升,Log4j 2 相较于 Log4j 和 Logback 都具有很明显的性能提升:https://logging.apache.org/log4j/2.x/performance.html#logging-library-performance-comparison
- 自动重载配置,参考了 Logback 的设计,当然会提供自动刷新参数配置,最实用的就是在生产环境中可以动态地修改日志的级别而不需要重启应用
- 无垃圾机制,Log4j 2 在大部分情况下,都可以使用其设计的一套无垃圾机制,避免频繁的日志收集导致的 JVM GC
官网:https://logging.apache.org/log4j/2.x/
目前市面上最主流的日志门面就是 SLF4J ,虽然 Log4j 2 也是日志门面,因为它的日志实现功能非常强大,性能优越。
所以一般还是将 Log4j 2 看作是日志的实现,SLF4J + Log4j 2 应该是未来的大势所趋。
示例 初次使用
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">
    <modelVersion>4.0.0</modelVersion>
    <groupId>io.github.jihch</groupId>
    <artifactId>log4j2-demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <!-- Log4j 2 的日志门面 -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.11.1</version>
        </dependency>
        <!-- Log4j 2 的日志实现 -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.11.1</version>
        </dependency>
        <!-- JUnit 单元测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
</project>
Log4j2Test.java
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;
public class Log4j2Test {
    // 定义日志记录器对象
    public static final Logger LOGGER = LogManager.getLogger(Log4j2Test.class);
    //快速入门
    @Test
    public void testQuick() {
        // 日志消息输出
        LOGGER.fatal("fatal");
        LOGGER.error("error");
        LOGGER.warn("warn");
        LOGGER.info("info");
        LOGGER.debug("debug");
        LOGGER.trace("trace");
    }
}
ERROR StatusLogger No Log4j 2 configuration file found. Using default configuration (logging only errors to the console), or user programmatically provided configurations. Set system property 'log4j2.debug' to show Log4j 2 internal initialization logging. See https://logging.apache.org/log4j/2.x/manual/configuration.html for instructions on how to configure Log4j 2
10:55:13.961 [main] FATAL io.github.jihch.Log4j2Test - fatal
10:55:13.963 [main] ERROR io.github.jihch.Log4j2Test - error
可以看出 Log4j 2 的日志级别默认是 error;
还有警告信息:未找到 Log4j 2 配置文件
示例 加入配置文件
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" monitorInterval="5">
    <properties>
        <property name="LOG_NAME">E:/logs</property>
    </properties>
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] [%-5level] %c{36}:%L --- %m%n" />
        </Console>
        <File name="file" fileName="${LOG_HOME}/myfile.log">
            <PatternLayout pattern="[%d{HH:mm:ss.SSS}] [%-5level] %l %c{36} - %m%n" />
        </File>
        <RandomAccessFile name="accessFile" fileName="${LOG_HOME}/myAcclog.log">
            <PatternLayout pattern="[%d{HH:mm:ss.SSS}] [%-5level] %l %c{36} - %m%n" />
        </RandomAccessFile>
        <RollingFile name="rollingFile" fileName="${LOG_HOME}/myrolling.log"
                     filePattern="E:/logs/$${date:yyyy-MM-dd}/myrolllog-%d{yyyy-MM-dd-HH-mm}-%i.log">
            <ThresholdFilter level="debug" onMatch="ACCEPT" onMismatch="DENY" />
            <PatternLayout pattern="[%d{HH:mm:ss.SSS}] [%-5level] %l %c{36} - %m%n" />
            <Policies>
                <OnStartupTriggeringPolicy />
                <SizeBasedTriggeringPolicy size="10MB" />
                <TimeBasedTriggeringPolicy />
            </Policies>
            <DefaultRolloverStrategy max="30"/>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="trace">
            <AppenderRef ref="Console" />
        </Root>
    </Loggers>
</Configuration>
再次运行:
11:17:15.000 [main] [FATAL] io.github.jihch.Log4j2Test:17 --- fatal
11:17:15.003 [main] [ERROR] io.github.jihch.Log4j2Test:18 --- error
11:17:15.003 [main] [WARN ] io.github.jihch.Log4j2Test:19 --- warn
11:17:15.004 [main] [INFO ] io.github.jihch.Log4j2Test:20 --- info
11:17:15.004 [main] [DEBUG] io.github.jihch.Log4j2Test:21 --- debug
11:17:15.004 [main] [TRACE] io.github.jihch.Log4j2Test:22 --- trace
配置文件在 Appenders 中声明了多个 Appender;
在 Loggers 中为 Root 指定了日志级别为 “trace”,使用的 Appender 是 name=“Console”的 Appender;
所以控制台中出现了对应配置的日志记录
示例 使用 SLF4J 作为日志门面,Log4j 2 作为日志实现
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">
    <modelVersion>4.0.0</modelVersion>
    <groupId>io.github.jihch</groupId>
    <artifactId>log4j2-demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <!-- 使用 SLF4J 作为日志门面 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.26</version>
        </dependency>
        <!-- 使用 Log4j 2 的适配器进行绑定 -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <version>2.9.1</version>
        </dependency>
        <!-- Log4j 2 的日志门面 -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.11.1</version>
        </dependency>
        <!-- Log4j 2 的日志实现 -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.11.1</version>
        </dependency>
        <!-- JUnit 单元测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
</project>
SLF4JTest.java
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SLF4JTest {
    public static final Logger LOGGER = LoggerFactory.getLogger(SLF4JTest.class);
    @Test
    public void test() {
        // 日志输出
        LOGGER.error("error");
        LOGGER.warn("warn");
        LOGGER.info("info");
        LOGGER.debug("debug");
        LOGGER.trace("trace");
    }
}
11:28:45.483 [main] [ERROR] io.github.jihch.SLF4JTest:14 --- error
11:28:45.485 [main] [WARN ] io.github.jihch.SLF4JTest:15 --- warn
11:28:45.485 [main] [INFO ] io.github.jihch.SLF4JTest:16 --- info
11:28:45.485 [main] [DEBUG] io.github.jihch.SLF4JTest:17 --- debug
11:28:45.485 [main] [TRACE] io.github.jihch.SLF4JTest:18 --- trace