Log4j1X迁移至Log4j2(基于SLF4j)

时间:2021-12-20 22:52:59

Log4j2相比Log4j1有很大的性能提升,由其是AsyncAppender,因此还是很有升级的必要。

迁移之前要注意以下几点:

  • Log4j2不再支持.properties配置文件,增加了JSON格式支持
  • XML配置文件有较大变动

修改pom.xml

删除老的所有关于日志的依赖,改为:

<!-- logging -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.4</version>
</dependency>

修改XML

  • 首先要把log4j.xml更名为log4j2.xml
  • 去掉doctype声明
    如:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd">
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>
</log4j:configuration>

直接改为:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
</Configuration>
  • Appenderlogger全部放到<Appenders><Loggers>标签下

From:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd">
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
</layout>
</appender>
<category name="org.apache.log4j.xml">
<priority value="info" />
</category>
<Root>
<priority value ="debug" />
<appender-ref ref="STDOUT" />
</Root>
</log4j:configuration>

To:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Appenders>
<Console name="STDOUT" target="SYSTEM_OUT">
<PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
</Console>
</Appenders>
<Loggers>
<Logger name="org.apache.log4j.xml" level="info"/>
<Root level="debug">
<AppenderRef ref="STDOUT"/>
</Root>
</Loggers>
</Configuration>
  • Log4j2不再通过class属性区分appender的类型,而是直接通过标签名
    例如,控制台appender From:
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
</layout>
</appender
>

To:

<Console name="STDOUT" target="SYSTEM_OUT">
<PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
</Console>

看起来简洁了许多,不过还是增加了查文档的时间成本。

XML文件的变动让人很不舒服,但是还是值得折腾一下的。完成以上工作后Log4j2应该就能正常工作了。更详细的配置说明可以参考http://logging.apache.org/log4j/2.x/manual/migration.html