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

是否可以覆盖已在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来查找类标记。

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

非常感谢提前!

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

旧问题(在谷歌索引)。 除了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 
  • 如果选择此选项,则必须在执行行中提供