本文介绍了以编程方式覆盖log4j配置:FileAppender的文件位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以覆盖已在 log4j.properties 中配置的appender的File属性而无需创建新的appender?
如果是这样 - 怎么样?

is it possible to override the "File" property of an appender that has been configured in the log4j.properties without creating a new appender?And if so - how?

情况如此:我有两个分配器,A1是ConsoleAppender,A2是FileAppender。 A2的文件指向一般错误.log:

This is the situation: I have two apenders, A1 is a ConsoleAppender and A2 is a FileAppender. A2's "File" points a generic error.log:

log4j.appender.A2.File = error.csv

此appender仅记录错误级别事件或更糟糕地通过

This appender only logs error-level events or worse through

log4j.appender .A2.Threshold =错误

现在我希望将这些错误写入不同的文件,具体取决于导致错误的类,因为那里是几个正在创建实例的类。
能够快速查看哪个类创建错误会有很大的帮助,因为它更有用,然后浏览error.log来查找类标记。

Now I want those errors to be written in different files depending on which class caused the error, as there are several classes that instances are being created of.Being able to see which class created the error(s) fast would be of great help, as it is a lot more helpful then skimming through the error.log looking for the class-tags.

所以我的想法是覆盖文件属性,例如在这些新创建的类的构造函数中,所以他们将错误记录在不同的文件中。

So my idea was to override the "File" property e.g. in the constructors of these newly created classes, so they log errors in different files.

提前多多感谢!

推荐答案

要在运行时更改log4j属性,请访问此链接

For changing log4j properties on runtime visit this link

 private void updateLog4jConfiguration(String logFile) { 
    Properties props = new Properties(); 
    try { 
        InputStream configStream = getClass().getResourceAsStream( "/log4j.properties"); 
        props.load(configStream); 
        configStream.close(); 
    } catch (IOException e) { 
        System.out.println("Error: Cannot laod configuration file "); 
    } 
    props.setProperty("log4j.appender.FILE.file", logFile); 
    PropertyConfigurator.configure(props); 
 }

这篇关于以编程方式覆盖log4j配置:FileAppender的文件位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 04:30