Green
Green

Reputation: 1465

How can I change the RollingFileAppender to another than the one set in config file?

I'm using log4j in my app, and a config file that sets up output to console and a rollingfileappender. Pasting config file below. Is there a way to change the fileappender output file after opening the config file in code? It opens fine for me, but there are times when I will want to use a different output file than the default one in the config file. Thanks for any direction.

log4j.rootLogger=info, stdout, RFA

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=[%p] [%d{MM/dd/yyyy HH:mm:ss}] - %m %n

log4j.appender.RFA=org.apache.log4j.RollingFileAppender
log4j.appender.RFA.File=${user.home}/output.log

log4j.appender.RFA.MaxFileSize=100KB
# Keep backup files
log4j.appender.RFA.MaxBackupIndex=5

log4j.appender.RFA.layout=org.apache.log4j.PatternLayout
log4j.appender.RFA.layout.ConversionPattern=[%p] [%d{MM/dd/yyyy HH:mm:ss}] - %m %n

Upvotes: 1

Views: 2633

Answers (3)

Paaske
Paaske

Reputation: 4403

If you mean to edit the properties file from your code and have log4j detect it you'll have to make log4j monitor the properties file first by calling PropertyConfigurator.configureAndWatch("log4j.properties")

However, I'd prefer to access the appenders programatically using the Logger api like kunal mentioned.

update; code for doing it programatically

Enumeration allAppenders = Logger.getRootLogger().getAllAppenders();
while (allAppenders.hasMoreElements()) {
    Object object = (Object) allAppenders.nextElement();
    if (object instanceof RollingFileAppender) {
        RollingFileAppender appender = (RollingFileAppender) object;
        appender.setFile("/path/to/new/file.log");
        appender.activateOptions();
        break;
    }
}

Upvotes: 3

kdabir
kdabir

Reputation: 9868

I think you want to set (change) the File programmatically. Have a look at the RollingFileAppender API.

public void setFile(String fileName,
                    boolean append,
                    boolean bufferedIO,
                    int bufferSize)
             throws IOException

Sets and opens the file where the log output will go. The specified file must be writable.

Upvotes: 0

DwB
DwB

Reputation: 38328

define another appender (with a different File value).

Upvotes: 0

Related Questions