3-log4j2之输出日志到文件

时间:2023-12-23 22:33:49

一、添加maven依赖

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

二、log4j2.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<properties>
<Property name="console-pattern">%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] [%level] %logger{36} - %msg%n</Property>
<property name="error-file">log4j2learn.log</property>
</properties>
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="${console-pattern}" />
</Console> <File name="FileAppender" fileName="${error-file}" >
<PatternLayout pattern="${console-pattern}" />
</File> <Async name="AsyncAppender">
<AppenderRef ref="FileAppender"/>
</Async>
</Appenders> <Loggers>
<Root level="info">
<AppenderRef ref="Console" />
<appenderRef ref="AsyncAppender" />
</Root>
<Logger name="AsyncFileLogger" level="error" additivity="false">
<appenderRef ref="AsyncAppender" />
</Logger>
</Loggers> </Configuration>

三、测试代码

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; /**
* @author : zhangyanqing
* @time : 2017/12/9
* @desc : 输出日志到文件
*/
public class FileLoggerTest {
public static final Logger LOGGER = LogManager.getLogger("AsyncFileLogger");
public static void main(String[] args){
LOGGER.trace("trace level");
LOGGER.debug("debug level");
LOGGER.info("info level");
LOGGER.warn("warn level");
LOGGER.error("error level");
LOGGER.fatal("fatal level");
}
}