I'm trying to add a log4j2 file appender at runtime.  I have a process that has 
it's own log4j2.xml config file which logs to a rolling file appender and the 
console.  This process will receive requests from other processes.  It creates 
an output folder that I want to create a log file in for the output during that 
run.  So, I add a file appender in code, then remove it when the job is 
complete.  This worked in log4j 1.x but doesn't work now that I updated to 
log4j2.  Here's the code to add the appender:

         final LoggerContext loggerContext = (LoggerContext) 
LogManager.getContext(false);
         final Configuration config = loggerContext.getConfiguration();
         FileAppender appender =
               
FileAppender.newBuilder().withName("MyFileAppender").withAppend(false)
               .withFileName(new File(myOutputDirectory, "log.txt").toString())
                     .withLayout(
                           PatternLayout.newBuilder().withPattern("%d [%t] %-5p 
%c - %m%n").build())
               .setConfiguration(loggerContext.getConfiguration()).build();
         appender.start();
         config.addAppender(appender);
         
loggerContext.getRootLogger().addAppender(loggerContext.getConfiguration().getAppender(appender.getName()));
         loggerContext.updateLoggers();

The log.txt file is create but nothing is written to it.  I also close the 
appender like this:

         if (appender != null && loggerContext != null)
         {
            appender.stop();
            Configuration config = loggerContext.getConfiguration();
            config.getRootLogger().removeAppender("OOEngineFileAppender");
            loggerContext.getRootLogger().removeAppender(appender);
            loggerContext.updateLoggers();
         }

Any idea what I'm doing wrong?

BTW, I turned on log4j2 debug via the command line switch and I see this output 
when I add the new appender:

    DEBUG StatusLogger Not in a ServletContext environment, thus not loading 
WebLookup plugin.
    DEBUG StatusLogger PluginManager 'Converter' found 44 plugins
    DEBUG StatusLogger Starting OutputStreamManager SYSTEM_OUT.false.false-2
    DEBUG StatusLogger Starting FileManager 
e:\temp\OutputDir\TaskRun_20190402_215311_122\log.txt

Thanks,
-Mike

Reply via email to