0

I would need a custom appender for log4j2 that I programmatically plug in (I do not want to alter log4j2.xml, as I need that appender to be used by default). For custom appender, there seems to be an answer How to Create a Custom Appender in log4j2?, but how I can add appender at run-ti,e?

onkami
  • 8,791
  • 17
  • 90
  • 176
  • 1
    This might help https://stackoverflow.com/questions/10699358/log4j-creating-modifying-appenders-at-runtime-log-file-recreated-and-not-appe – luso Mar 22 '18 at 09:14

1 Answers1

1

Basically you need to instantiate the appender and after it plug it into desired log. In this example I am using ConsoleAppender and rootLogger

LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
Configuration config = ctx.getConfiguration();
ConsoleAppender consoleAppender = ConsoleAppender.
              createDefaultAppenderForLayout(PatternLayout.createDefaultLayout());
consoleAppender.start(); // this is optional
config.addAppender(consoleAppender);  // this is optional
ctx.getRootLogger().addAppender(consoleAppender);
ctx.updateLoggers();
Anton Balaniuc
  • 10,889
  • 1
  • 35
  • 53