在 Java 中禁用 Log4J 输出

如何使用 log4j.properties文件快速关闭所有 日志4J输出?

156285 次浏览

Set level to OFF (instead of DEBUG, INFO, ....)

You can change the level to OFF which should get rid of all logging. According to the log4j website, valid levels in order of importance are TRACE, DEBUG, INFO, WARN, ERROR, FATAL. There is one undocumented level called OFF which is a higher level than FATAL, and turns off all logging.

You can also create an extra root logger to log nothing (level OFF), so that you can switch root loggers easily. Here's a post to get you started on that.

You might also want to read the Log4J FAQ, because I think turning off all logging may not help. It will certainly not speed up your app that much, because logging code is executed anyway, up to the point where log4j decides that it doesn't need to log this entry.

 log4j.rootLogger=OFF

If you want to turn off logging programmatically then use

List<Logger> loggers = Collections.<Logger>list(LogManager.getCurrentLoggers());
loggers.add(LogManager.getRootLogger());
for ( Logger logger : loggers ) {
logger.setLevel(Level.OFF);
}

Change level to what you want. (I am using Log4j2, version 2.6.2). This is simplest way, change to <Root level="off">

For example: File log4j2.xml
Development environment

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
<Console name="SimpleConsole" target="SYSTEM_OUT">
<PatternLayout pattern="%msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="error">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
<Loggers>
<Root level="info">
<AppenderRef ref="SimpleConsole"/>
</Root>
</Loggers>
</Configuration>

Production environment

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
<Console name="SimpleConsole" target="SYSTEM_OUT">
<PatternLayout pattern="%msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="off">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
<Loggers>
<Root level="off">
<AppenderRef ref="SimpleConsole"/>
</Root>
</Loggers>
</Configuration>

In addition, it is also possible to turn logging off programmatically:

Logger.getRootLogger().setLevel(Level.OFF);

Or

Logger.getRootLogger().removeAllAppenders();
Logger.getRootLogger().addAppender(new NullAppender());

These use imports:

import org.apache.log4j.Logger;
import org.apache.log4j.Level;
import org.apache.log4j.NullAppender;