10
votes

Is there any way I can remove appender from a logger in log4j2 programmatically ?

The website says "Log4j 2 API does not expose methods to add, modify or remove appenders and filters or manipulate the configuration in any way" : https://logging.apache.org/log4j/2.x/manual/configuration.html

But i would really appreciate if someone can suggest an indirect way to achieve this.

Thanks.

4
Can you provide a sample configuration file and what do you from that? - sazzad

4 Answers

8
votes

There is a method LoggerConfig#removeAppender(String name) which will remove specific appender and LoggerConfig#clearAppenders() which will remove all appenders. Let's say you have an appender with the name CONSOLE:

final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration();
config.getRootLogger().removeAppender("CONSOLE");
ctx.updateLoggers();
2
votes

Developing an idea of Anton (on log4j 2.11.1):

LoggerContext context = LoggerContext.getContext(false);
Configuration configuration = context.getConfiguration();
LoggerConfig loggerConfig = configuration.getLoggerConfig("loggerName");
if (loggerConfig.getName().equals("loggerName")) {
    loggerConfig.removeAppender("appenderName")
} else {
    throw new RuntimeException("There was no logger " + "loggerName");
}
context.updateLoggers();
0
votes
LoggerContext loggerContext = (LoggerContext) LogManager.getContext(true);
Configuration configuration = loggerContext.getConfiguration();
LoggerConfig loggerConfig = configuration.getLoggerConfig(_logger.getName());
loggerConfig.getAppenders().forEach((key, value) -> loggerConfig.removeAppender(value.getName()));
-1
votes

Can you remove an Appender? Yes. Should you? Almost always the answer is no. What if a LoggerConfig, an AsyncAppender or a RoutingAppender is referencing the Appender? You will get an error.

In most cases you really want to use smarter filtering. They are there precisely to reduce or eliminate the number of events being routed to an Appender.