Turning on/off logs at runtime

2019-08-08 18:24发布

问题:

I am using SLF4J with Log4J for logging. So far I am using the log4j configuration from xml file. How I can turn on/off logging at runtime.

e.g. a web service turns on/off logs, so I will not have too much logs and will enable only for debugging purpose.

Thanks.

回答1:

log4j logger levels can be changed at runtime. Change the log4j logging level to error, so that all the debug and info statements will no be logged. If the application is restarted the logger level will be changed to the one defined in log4j.xml or log4j.properties.



回答2:

I found out that this disables the log4j completely:

org.apache.log4j.LogManager.resetConfiguration();
org.apache.log4j.LogManager.getRootLogger().addAppender(new NullAppender());

If you still want the logging but directed to a file you can do this:

LogManager.resetConfiguration();
LogManager.getRootLogger().addAppender(new FileAppender(new PatternLayout(), "log.log"));