Reputation: 9441
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?
Upvotes: 1
Views: 1401
Reputation: 11749
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();
Upvotes: 1