Denis Kulagin
Denis Kulagin

Reputation: 8947

Disable log4j output during unit-tests

It's common practice to obtain loggers via static-factory (though it totally brokes DI principle). And actually it's fine, unless you would like to get rid of logging totally, e.g. while running unit-tests.

I was able to switch off log4j logging, by using following spell:

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

Still it prints some setup info to the console in the very beginning:

log4j: reset attribute= "false".
log4j: Threshold ="null".
log4j: Retreiving an instance of org.apache.log4j.Logger.
log4j: Setting [test] additivity to [false].
log4j: Level value for test is  [DEBUG].
...

How do I disable it as well, programmatically, while running unit-test suite?

Upvotes: 17

Views: 36523

Answers (1)

Johan Boberg
Johan Boberg

Reputation: 3781

You probably have enabled internal log4j logging in your log4j.properties or log4j.xml file.

Log4j uses a class called LogLog to make these internal logging calls. You can disable LogLog's output by calling LogLog.setQuietMode(true). This needs to be set before the first call to log4j, which triggers initialization. Note, though, that setQuietMode() not only disables debug output but also warnings.

I would therefore recommend that you use a separate logging configuration for your tests. Raedwald outlined how to do this in the answer they linked to.

Here's an example log4j.xml file that you can use. Notice the debug="false" property. It's not strictly necessary to set this, though, as the default value is false.

If you're using maven, put the file in src/test/resources, which will ensure that this file will get picked up for tests instead of your main configuration file.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="false" xmlns:log4j='http://jakarta.apache.org/log4j/'>

    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n"/>
        </layout>
    </appender>

    <root>
        <level value="OFF"/>
        <appender-ref ref="console"/>
    </root>

</log4j:configuration>

This is the equivalent log4j.properties file:

log4j.debug=false

log4j.rootLogger=OFF, console

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

Upvotes: 21

Related Questions