Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove appender from logger in log4j2 programmatically?

Tags:

logging

log4j2

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.

like image 669
user122345656 Avatar asked Jan 13 '17 07:01

user122345656


People also ask

What is Appender logger?

The appender is the part of a logging system that's responsible for sending the log messages to some destination or medium. It answers the question "where do you want to store this stuff?"

How do you change the log level in log4j2 at runtime?

You can set a logger's level with the class Configurator from Log4j Core. BUT be aware that the Configurator class is not part of the public API. If you wish to change the root logger level, do something like this : LoggerContext ctx = (LoggerContext) LogManager.

What is logger and Appender in Log4j?

Log4j allows logging requests to print to multiple destinations. In log4j speak, an output destination is called an appender. Currently, appenders exist for the console, files, GUI components, remote socket servers, JMS, NT Event Loggers, and remote UNIX Syslog daemons. It is also possible to log asynchronously.

What is JMS Appender log4j2?

Log4j JMS appender can be used to send your log messages to JMS broker. To use ActiveMQ as a destination of your messages, you need to configure JMS appender properly.


2 Answers

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();
like image 96
Timofey Gorshkov Avatar answered Oct 18 '22 10:10

Timofey Gorshkov


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();
like image 42
Anton Balaniuc Avatar answered Oct 18 '22 10:10

Anton Balaniuc