Log4J change File path dynamically

早过忘川 提交于 2020-01-10 08:57:08

问题


I want to change the path and file name of my log4j logfile dynamically.

I have read a lot of pages and nearly every tell me that I should use system properties like here: how to change the log4j log file dynamically?

So my log4j.properties file looks like this:

log4j.logger.JDBC_LOGGER=INFO,jdbcTests
log4j.additivity.JDBC_LOGGER = false

log4j.appender.jdbcTests=org.apache.log4j.FileAppender
log4j.appender.jdbcTests.File=${my.log}
log4j.appender.jdbcTests.layout=org.apache.log4j.PatternLayout
log4j.appender.jdbcTests.append = false
log4j.appender.jdbcTests.layout.ConversionPattern=%d{yyyy mm dd HH:mm:ss} %5p %C:Line %L - %m%n

In my main method I am going to set my new system property:

System.setProperty("{my.log", "C:/logfile.log");

But I just get an error:

log4j:ERROR setFile(null,false) call failed.
java.io.FileNotFoundException: 
    at java.io.FileOutputStream.open(Native Method)....

And when I try to read my set system property with:

System.out.println(System.getProperty("my.log"));

it return null. What do I do wrong?


回答1:


I think you meant "my.log" not "{my.log"

System.setProperty("my.log", "C:/logfile.log");

I wouldn't imagine you can change this once the logging has started so you need to set this as early in your program as possible.

BTW: You can sub-class FileAppender to make it behave any way you like.

|improve this answer

来源:https://stackoverflow.com/questions/11846593/log4j-change-file-path-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!