In my current project I need to make a certain task create its own logfile separate from what is configured in log4j.properties.
I try to achieve this by attaching a dynamically created FileAppender to the rootLogger:
public static void setupAnalysisLogfile(String filename) {
PatternLayout layout
= new PatternLayout("%d{dd MMM yyyy HH:mm:ss,SSS} [%t] %-5p %C{1} %x - %m%n");
if(Config.CREATE_SEPERATE_LOG)
{
FileAppender appender;
try {
String path = (Config.LOGFILE_PATH!=null)?Config.LOGFILE_PATH:filename;
appender = new FileAppender(layout,path);
appender.setName("Analysis Appender");
org.apache.log4j.Logger.getLogger("my.package.hierarchy").addAppender(appender);
} catch (IOException e) {
org.apache.log4j.Logger.getLogger(Config.class).warn(
"Failed to create a dedicated log "
+ filename,
e);
}
}
}
When Config.LOGFILE_PATH is not null (comes from a commandline parameter) everything works. The logfile is created in the specified path.
However, when LOGFILE_PATH is null no logfile is created, or rather nothing is ever written to it.
Running the program with -Dlog4j.debug gives:
log4j: setFile called: /home/tbender/.something/bytecode/OMFG_3527961e3fb1134e1d3221c000879a90ff1022b6/bytecode/OMFG-1340994475441.log, true
log4j: setFile ended
When I step through the code and keep an eye on the list of open filehandles, I can see that the filehandle is created during the creation of the appender. Once the application finishes no logfile exists.
Any ideas?
Okay in the end it was not FileAppend that caused to problem but a totally unrelated piece of code that deleted and recreated the folder where my logfile was residing. D’OH!
Good tip for trouble like this: When you are in linux use strace:
That will show you what files were created, oepened, closed or removed. You can also include a bunch of other stuff. More calls can be found here