Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically turn on or off one appender of rootLogger in log4j2?

Tags:

java

log4j

log4j2

How to dynamically turn on or off one appender of rootLogger in log4j2 by java at runtime?

for example, I wanna disable Console Appender:

...
    <Loggers>
        <Root level="INFO">
            <AppenderRef ref="Console"/>
            <AppenderRef ref="RollingFile"/>
        </Root>
    </Loggers>
...

Is it possible?

like image 594
Amin Sh Avatar asked May 11 '14 07:05

Amin Sh


People also ask

What is Rootlogger in Log4j2?

This concept is known as Logger Hierarchy. Logger Hierarchy is made up of set of LoggerConfig objects with a parent-child relationship. The topmost element in every Logger Hierarchy is the Root Logger. If Log4j2 doesn't find the configuration file, only Root Logger will be used for logging with logging level as ERROR.

What is rolling file Appender in Log4j2?

Log4j2 RollingFileAppender is an OutputStreamAppender that writes log messages to files, following a configured triggering policy about when a rollover (backup) should occur. It also has a configured rollover strategy about how to rollover the file.

What is configuration status in Log4j2?

Configuration: the root element of a log4j2 configuration file; the status attribute represents the level at which internal log4j events should be logged. Appenders: this element contains a list of appenders; in our example, an appender corresponding to the System console is defined.


1 Answers

You can programmatically add or remove an appender. In your case let's remove Console

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

There is a LifeCycle interface with methods stop and start, but it looks like you can not restart an appender after it was stopped.

like image 61
Anton Balaniuc Avatar answered Sep 19 '22 12:09

Anton Balaniuc