以编程方式覆盖log4j配置:FileAppender的文件位置

时间:2013-01-09 17:05:37

标签: java properties log4j override

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

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

log4j.appender.A2.File=error.csv

此appender仅记录错误级别事件或更糟糕的

log4j.appender.A2.Threshold=error

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

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

提前多多感谢!

2 个答案:

答案 0 :(得分:15)

要在运行时更改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); 
 }

答案 1 :(得分:10)

旧问题(在google中编入索引)。除了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);

VM选项

您可以使用log4j.configuration VM选项

告诉log4j加载其他文件
java -Dlog4j.configuration=file:///etc/myapp/properties/custom-log4j.properties
  • 如果选择此选项,则必须在执行行中提供