1

I'm trying to run a test for my class which uses java.util.logging.Logger

import java.util.logging.Logger;

public class TestLogging {
    final Logger logger = Logger.getLogger("Test");

    public void f1() {
        logger.entering(getClass().getName(), "f1");

        logger.info("f1");
        logger.fine("f1");
        logger.finer("f1");
        logger.finest("f1");

        logger.exiting(getClass().getName(), "f1");
    }
}

So I setup a test class to check if logger produces an output while the class is being tested

import org.junit.Before
import org.junit.Test
import java.util.logging.Level
import java.util.logging.Logger

class TestLogger {
    @Before
    fun setupLogger() {
        Logger.getLogger("Test").level = Level.FINEST
    }

    @Test
    fun test() {
        TestLogging().f1()
    }
}

But when I run it I only see the following output, as if the level is set to default.

TestLogger > test STANDARD_ERROR
    Sep 27, 2017 2:17:32 PM TestLogging f1
    INFO: f1
jmehrens
  • 10,580
  • 1
  • 38
  • 47
Philipp Grigoryev
  • 1,985
  • 3
  • 17
  • 23

1 Answers1

3

You have to hold a strong reference to your logger that is wider than method local scope. If you don't do that your level setting can be lost due to garbage collection of the logger.

If you want to see the output in the console then you also have to adjust the level of the console handler.

If you want to assert some output value then you need to install a filter or handler to look for a specific LogRecord.

jmehrens
  • 10,580
  • 1
  • 38
  • 47