Search code examples
javaloggingjunit5slf4j

Change logger level within one same junit5 unit test


What I would like to achieve:

I would like to change the logger level within the junit5 unit test.

Background:

I have a piece of code I would like to test which looks like this:

    public void question(final Foo foo) {
        if (LOGGER.isInfoEnabled() && someConditionVerified(foo)) {
            LOGGER.debug("condition has been verified on Foo");
        }
    }

And I would like to change the first condition of the if statement, the log level. From there, test if the log statement got printed.

What I have tried:

In order to do the above, I wrote this:

    @Test
    void testLogPrintedBasedOnLogLevel(CapturedOutput output) {
        //set the logger to NOT debug, like maybe info level, the log statment should not be printed
        question(new Foo());
        assertFalse(output.getOut().contains("condition has been verified on Foo"));
        //set the logger to debug so the log can be printed
        question(new Foo());
        assertTrue(output.getOut().contains("condition has been verified on Foo"));
    }

Question:

I am having a hard time changing the log level within the unit test.

I.e. I am having a hard time with the two commented lines. Could you please help?


Solution

  • If you are using slf4j (as tagged) then just try this:

    import org.slf4j.LoggerFactory;
    

    If Using Logback as the Logger Implementation

    import ch.qos.logback.classic.Level;
    import ch.qos.logback.classic.Logger;
    

    If Using Log4j 2 as the Logger Implementation

    import org.apache.log4j.Level;
    import org.apache.log4j.Logger;
    import org.apache.logging.log4j.core.config.Configurator
    

    If Using Java Util Logging

    import java.util.logging.Level;
    import java.util.logging.Logger;
    

    The code below assumes use of Logback (if using log4j 2 then you would use the Configurator to set the Level):

    Logger testLogger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    testLogger.setLevel(Level.INFO);
    

    or if in a Test Class (i.e. xxx) and different logger then try :

    Logger xxxLogger = (Logger) LoggerFactory.getLogger(xxx.class);
    xxxLogger .setLevel(Level.INFO);