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
495 views
in Technique[技术] by (71.8m points)

java - Log4j : Creating/Modifying appenders at runtime, log file recreated and not appended

I want to create and enable an appender for a particular method call MyMethod(), whose log output is supposed to go to a file present at "logFilePath".

I do not want to include this appender in the xml configuration file, so I thought to create it at run time.

First, I tried to modify the logger properties at runtime and then calling activateOptions, eg. setting level to DEBUG before and setting it to Off in the finally block, so that output is logged only while the method is in use. That didn't work.

My problem here is that appender recreates a file everytime, and does not append to the same file. This is inspite of setAppend being true.

I am not very familiar with log4j, so please feel free to suggest an alternative approach. The following is sample code to explain what I am trying.

private static FileAppender createNewAppender(String logFilePath) {
    FileAppender appender = new FileAppender();
    appender.setName("MyFileAppender");
    appender.setLayout(new PatternLayout("%d %-5p [%c{1}] %m%n"));
    appender.setFile(logFilePath);
    appender.setAppend(true);
    appender.setThreshold(Level.INFO);
    appender.activateOptions();
    Logger.getRootLogger().addAppender(appender);
    return appender;
}

private static void removeAppender() {
    Logger.getRootLogger().removeAppender(fileAppender) ; // ("MyFileAppender");
}

I call the above methods in the following way:

private static FileAppender fileAppender = null;

private static void myMethod(String logFilePath) {        
    try {
        fileAppender = createNewAppender();
        someOperation();
    }
    finally {
        removeAppender();
        fileAppender=null; 
    }
}
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

very easy just create a method and add this

String targetLog="where ever you want your log"

FileAppender apndr = new FileAppender(new PatternLayout("%d %-5p [%c{1}] %m%n"),targetLog,true);    
logger.addAppender(apndr);
logger.setLevel((Level) Level.ALL);

then in any method you need to log just do this: logger.error("your error here");


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

...