问题
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.
回答1:
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:
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();
回答3:
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.
来源:https://stackoverflow.com/questions/41629360/how-to-remove-appender-from-logger-in-log4j2-programmatically