16

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?

Amin Sh
  • 2,684
  • 2
  • 27
  • 42
  • 1
    IMO you will need to add the appenders programmatically, if you want to manipulate them through code. Here are some similar questions http://stackoverflow.com/questions/10699358/log4j-creating-modifying-appenders-at-runtime-log-file-recreated-and-not-appe and http://stackoverflow.com/questions/1909871/how-can-i-access-the-configured-log4j-appenders-at-runtime – Hirak May 11 '14 at 07:43
  • I don't have a lots of context. But maybe you can disable/enable it via JMX at runtime? – drgn Nov 23 '15 at 15:29

2 Answers2

6

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.

Anton Balaniuc
  • 10,889
  • 1
  • 35
  • 53
  • Why not to call stop() method after .removeAppender() method? Why one cannot restart an appender? – Gaurav Jul 18 '19 at 11:46
0

You could add a script filter to the console appenderref that checks the value of a system property. Then just set the property when you want logging to the console disabled. Reset it when you want it turned back on.

rgoers
  • 8,696
  • 1
  • 22
  • 24