近期,碰到需要将项目中的Log4J1升级到Log4J2,现进行下总结。交代下技术背景:web项目,基于Java + Maven
1. 依赖
<dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.3</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.3</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.2</version> </dependency> <!-- slf4j到log4j2的桥梁 --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <version>2.3</version> </dependency> <!-- listener:Log4jServletContextListener依赖 --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-web</artifactId> <version>2.3</version> <scope>runtime</scope> </dependency>
PS:slf4j-log4j12与log4j-slf4j-impl冲突,注意exclusion间接引入的slf4j-log4j12
2. 日志配置
配置log4j2.xml,放于classpath:log/log4j2.xml,或其他位置,则要注意修改下面web.xml中的响应配置
<?xml version="1.0" encoding="UTF-8"?> <Configuration status="off"> <Appenders> <Console name="STDOUT" target="SYSTEM_OUT"> <PatternLayout pattern="[%d] %-5p [%c %L] %m%n"/> </Console> <RollingFile name="AppAppender" fileName="/data/applogs/{项目名称}/logs/app.log" filePattern="/data/applogs/{项目名称}/logs/app.log.%d{yyyy-MM-dd}"> <PatternLayout> <Pattern>[%d] %-5p [%c %L] %m%n</Pattern> </PatternLayout> <Policies> <!-- 每天切割日志 --> <TimeBasedTriggeringPolicy interval="24" modulate="true"/> </Policies> </RollingFile> </Appenders> <Loggers> <Root level="info"> <AppenderRef ref="STDOUT"/> <AppenderRef ref="AppAppender"/> </Root> </Loggers> </Configuration>
PS:
{项目名称} 需替换成自己的项目;
/data/applogs/{项目名称}/logs/app.log 设置日志文件的绝对路径
/data/applogs/{项目名称}/logs/app.log.%d{yyyy-MM-dd} 设置切割后日志的绝对路径
3. 读取配置
web.xml中增加读取log4j2.xml的配置:
<!--由Spring载入的Log4j配置文件位置 --> <context-param> <param-name>log4jConfiguration</param-name> <!-- log4j2.xml文件位置,注意与2中的相对应 --> <param-value>classpath:log/log4j2.xml</param-value> </context-param> <!-- the very first listene --> <listener> <listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class> </listener>
4 参考资料
slf4j与jul、log4j1、log4j2、logback的集成原理
时间: 2024-11-14 23:37:50