log4j2.xml路径的指定

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.Log4j2ConfigListenerlistener-class>
    listener>
    <context-param>
        <description>日志配置文件的路径description>
        <param-name>log4j.configurationFileparam-name>
        <param-value>log4j/log4j2.xmlparam-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 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

你可能感兴趣的:(---------【Java】,◆编程语言)