公司的项目决定升级log4j,因为log4j2有一个自动删除日志的功能,这样可以减轻运维的一些工作,而且在多线程环境下,log4j2的异步日志系统比log4j和logback提高了十倍的性能(吞吐量和延迟率),官方原文如下:
Log4j 2 contains next-generation Asynchronous Loggers based on the LMAX Disruptor library. In multi-threaded scenarios Asynchronous Loggers have 10 times higher throughput and orders of magnitude lower latency than Log4j 1.x and Logback.
因为是升级,原项目用的是log4j或者self4j打印日志,获取logger的方式不同
比如log4j:
import org.apache.log4j.Logger;
private static final Logger LOGGER = Logger.getLogger(xxxx.class);
比如self4j:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private static final Logger logger = LoggerFactory.getLogger(xxxx.class);
而如果用log4j2的话,API将有所不同:
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
private static final Logger logger = LogManager.getLogger(xxxx.class);
如果在升级的过程中,我们要去改代码的话,那将是一项很大的繁琐工程,log4j2架构已经考虑到这一点,给我们提供了转换的包,我们只需要导入几个转换包就可以使用log4j2,而且还不需要修改代码。
官方原文:
Perhaps the simplest way to convert to using Log4j 2 is to replace the log4j 1.x jar file with Log4j 2's log4j-1.2-api.jar. However, to use this successfully applications must meet the following requirements:
删掉pom.xml文件中关于log4j的依赖,添加新依赖
org.apache.logging.log4j
log4j-api
2.7
org.apache.logging.log4j
log4j-1.2-api
2.7
org.apache.logging.log4j
log4j-core
2.7
org.apache.logging.log4j
log4j-web
2.7
runtime
log4j-1.2-api为log4j和log4j2的连接包。
第二步:删掉以前的log4j.properties,改为log4j2.xml,这里起名字的时候,不要写错了
${sys:catalina.base}/var/logs
${LOG_HOME}/uas
%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %class{36} %L %M --
%msg%xEx%n
这里需要注意的有以下几点:
1.log4j2.*版本中获取home路径是${sys:catalina.base}
2.要在
第三步:在web.xml中配置
注释掉以前关于加载log4j的配置,重新配置,这里我的log4j2.xml放在classpath/conf下
log4jConfiguration
classpath:conf/log4j2.xml
配置放在web.xml的
如此log4j升级log4j2升级成功。
扩展:如果原项目中用的是self4j打印日志,那么导包的时候需要导入:
org.slf4j
slf4j-api
${slf4j.version}
org.slf4j
slf4j-log4j12
${slf4j.version}
也是不需要修改代码,关于self4j继承log4j2的详细解决方案,可参考: http://blog.csdn.net/zouxucong/article/details/56005725