log4j2.xml路径的指定

时间:2022-03-15 23:16:17

log4j2.xml的路径的指定

我们使用log4j2一般做法是将log4j2.xml文件放在资源文件夹根目录。对于有强迫症的开发者来说,我更喜欢在资源文件夹下新建包或文件夹,然后把配置文件放在里面。本博客将介绍如何自定义log4j2.xml文件的位置和文件名。

可运行的jar中的指定

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.LoggerContext;


..........//省略

LoggerContext logContext = (LoggerContext) LogManager.getContext(false);
File conFile = new File("conf/logs/log4j2.xml");
logContext.setConfigLocation(conFile.toURI());
logContext.reconfigure();
logger.debug("hello world...{}","How are you");


........//省略



java web 中的指定

  • web.xml配置
    <!-- 系统日志配置监听器 -->
<listener>
<listener-class>edu.example.holder.system.Log4j2ConfigListener</listener-class>
</listener>
<context-param>
<description>日志配置文件的路径</description>
<param-name>log4j.configurationFile</param-name>
<param-value>log4j/log4j2.xml</param-value>
</context-param>

Log4j2ConfigListener类是自定义的类,实现ServletContextListener接口,这样tomcat启动时可以更改日志配置文件的默认路径和文件名。

  • 生效配置文件
package edu.example.holder.system;

import java.util.Enumeration;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.logging.log4j.core.config.Configurator;

public class Log4j2ConfigListener implements ServletContextListener
{

private static final String KEY = "log4j.configurationFile";

@Override
public void contextDestroyed(ServletContextEvent arg0)
{
}

@Override
public void contextInitialized(ServletContextEvent arg0)
{
String fileName = getContextParam(arg0);
Configurator.initialize("Log4j2", "classpath:" + fileName);
}

@SuppressWarnings("unchecked")
private String getContextParam(ServletContextEvent event) {
Enumeration<String> names = event.getServletContext().getInitParameterNames();
while (names.hasMoreElements())
{
String name = names.nextElement();
String value = event.getServletContext().getInitParameter(name);
if(name.trim().equals(KEY))
{
return value;
}
}
return null;
}
}

参考:
http://blog.csdn.net/wengengeng/article/details/53674160