Log4J2 - How to disable logging in unit test?
Asked Answered
A

3

24

I am using Log4J v2.0 Beta3 in my application for logging and I am getting log messages generated when I run my unit tests. I checked the API for some way to set the log level to something like CRITICAL but I could not find any way to change the logger configuration.

In fact, I read this on the log4j2 website:

Note that unlike Log4j 1.x, the public Log4j 2 API does not expose methods to add, modify or remove appenders and filters or manipulate the configuration in any way.

So with that said. What is the correct way to disable logging from within unit tests?

Apices answered 4/1, 2013 at 16:18 Comment(0)
A
30

I found my answer on the log4j2 website under 'Testing in Maven'. The recommended way seems to be to place a log4j2-test.xml file in src/test/resources. Placing the xml file into this directory will cause it to be used instead of a log4j2.xml.

Apices answered 4/1, 2013 at 16:28 Comment(1)
It would be good to provide an answer to specific question "how to disable". This answers "where to place configuration file for tests" instead.Ferdinande
F
6

You can disable logging with setting root level to off (<Root level="off"/>).

So place log4j2.xml file into src/test/resources with following content:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn">
    <Loggers>
        <Root level="off"/>
    </Loggers>
</Configuration>

EDIT: Removed <!DOCTYPE xml> (based on suggestion from sprynter) to make xml valid.

Fullblooded answered 27/11, 2018 at 22:32 Comment(1)
Remove the <!DOCTYPE xml> from the answer above for a valid log4j2 config file.Eatmon
D
1

Both the answers from @Jbug and @Dove work as long as you are placing the file in src/test/resources of the current module. If your app depends on a library to include log4j2.xml it won't work for test runs since library jar won't included test classes and resources.

Deign answered 10/11, 2019 at 21:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.