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?

有帮助吗?

解决方案

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.

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top