10

log4j.properties是否可以在不创建新附加程序的情况下覆盖已配置的附加程序的“文件”属性?如果是这样 - 如何?

情况是这样的:我有两个 appender,A1 是 ConsoleAppender,A2 是 FileAppender。A2 的“文件”指向一个通用的 error.log:

log4j.appender.A2.File=error.csv

此附加程序仅记录错误级别的事件或更糟糕的事件

log4j.appender.A2.Threshold=error.

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

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

提前非常感谢!

4

2 回答 2

17

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

http://alperkaratepe.wordpress.com/2010/01/16/how-to-change-log4j-properties-at-runtime/

 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); 
 }
于 2013-01-09T17:16:31.827 回答
13

老问题(在谷歌中有很好的索引)。除了 OP 的要求外,还添加了其他方法log4j.properties


log4j.properties在运行时加载的修改

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("Errornot laod configuration file "); 
    } 
    props.setProperty("log4j.appender.FILE.file", logFile); 
    LogManager.resetConfiguration(); 
    PropertyConfigurator.configure(props); 
}

log4j.properties在运行时设置

可以手动完成

Properties properties = new Properties();
properties.setProperty("log4j.logger.org.hibernate", "ERROR");
// ...

LogManager.resetConfiguration();
PropertyConfigurator.configure(properties);

或者通过加载不同的属性文件

Properties properties = new Properties();
properties.load(new FileInputStream("/etc/myapp/properties/custom-log4j.properties"));
LogManager.resetConfiguration();
PropertyConfigurator.configure(properties);

虚拟机选项

您可以告诉 log4j 使用log4j.configurationVM 选项加载不同的文件

java -Dlog4j.configuration=file:///etc/myapp/properties/custom-log4j.properties
  • 如果选择此选项,则必须在执行行中提供
于 2015-12-31T08:53:44.423 回答