`
Veromca-源代码
  • 浏览: 40599 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Log4j 动态更新配置文件【热配置】

阅读更多
由于项目要求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);
	}

}


1
1
分享到:
评论
1 楼 paven 2017-06-22  
根本无效的好吗

相关推荐

Global site tag (gtag.js) - Google Analytics