Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
550 views
in Technique[技术] by (71.8m points)

java - override log4j configuration programmatically: file location for FileAppender

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?

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

This appender only logs error-level events or worse through

log4j.appender.A2.Threshold=error.

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.

Thanks a lot in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For changing log4j properties on runtime visit this link

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); 
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...