Reputation: 3958
I need to add programmatically an appender (to console) to an existing logger in Log4j2.
I was able to do this in Log4j version 1.
How can I do this in version 2?
Upvotes: 2
Views: 2207
Reputation: 9151
Have you looked at the Log4j documentation? See Programmatically Modifying the Current Configuration after Initialization.
In your question you indicate you have an existing Logger. In Log4j 1 configuration was directly attached to Loggers, which makes it impossible to reconfigure without losing logging events. Log4j 2 separates the Loggers from their configuration by attaching the configuration to a LoggerConfig object and then directing Loggers to the appropriate LoggerConfig. So it isn't clear if you already have an existing LoggerConfig (which are normally created by the Logger definitions in your configuration file). If you do not then the example in the documentation will work. If you already have an existing LoggerConfig. You simply need to locate it by calling getLoggerConfig() on the existing Configuration and then add the appender reference to it. Note that the getLoggerConfig() may not return a LoggerConfig with the exact name you provided. It searches the hierarchy to find the existing LoggerConfig that the Logger will use, so modifying it may also impact other Loggers.
A simpler way to add an Appender to a Logger is to use the Configuration's addLoggerAppender() method. An example might be:
private void addAppender(Logger logger) {
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration();
Layout layout = PatternLayout.createLayout(PatternLayout.SIMPLE_CONVERSION_PATTERN, config, null,
null,null, null);
Appender appender = FileAppender.createAppender("target/test.log", "false", "false", "File", "true",
"false", "false", "4000", layout, null, "false", null, config);
appender.start();
config.addLoggerAppender(logger, appender);
}
Upvotes: 1