欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Log4j 动态更新配置文件【热配置】 博客分类: log4j log4jjava

程序员文章站 2024-02-25 23:39:51
...
由于项目要求Log4j需要支持热配置,研究了一下Log4j中实现修改配置文件后实时生效的方法,考虑到效率问题,最后采用了第二种方法,以下是具体实现实例:

一.使用log4j自带的动态更新配置文件【轮询方式来实现】:
主要调用 PropertyConfigurator 或者 DOMConfigurator类的 configureAndWatch(String configFileName)或者 configureAndWatch(String configFileName, long delay)来实现。

注意:在log4j中每调用一次configureAndWatch方法都会启动一个新的扫描线程。


public class TestLog4j
{
    public static Logger logger = Logger.getLogger(TestLog4j.class);
    static
    {
        PropertyConfigurator.configureAndWatch("./log4j.properties", 60000);
    }
    public static void printLog()
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("debug!!");
        }
        if (logger.isInfoEnabled())
        {
            logger.info("info!!");
        }
        logger.error("error!!");
    }
    public static void main(String[] args)
    {
        while (!Thread.interrupted())
        {
            TestLog4j.printLog();
            try
            {
                Thread.sleep(1000);
            } catch (InterruptedException e)
            {
            }
        }
    }
}



二.事件触发方式实现:
调用PropertyConfigurator对象或DOMConfigurator对象的configure(String configFilename)方法。

import org.apache.log4j.xml.DOMConfigurator;

public class TestLog4j
{

	
	/**
	 * 
	 * Description:reload Log4j.xml<br>
	 *
	 */
	private void reloadLog4jConfig(String filePaht)
	{
		DOMConfigurator.configure(filePath);//加载.xml文件 		
	} 
	
	/**
	 * Description:<br>
	 * 
	 * @param args
	 */
	public static void main(String[] args)
	{
		TestLog4j test = new TestLog4j();
		String filePaht =  "src/test/resources/log4j.xml";
		test.reloadLog4jConfig(filePaht);
	}

}


相关标签: log4j java