Search code examples
javaunit-testinglogginglog4jlog4j2

How to write a unit test for a custom logger in log4j2


I've created a couple of custom loggers with some levels that override the custom ones in Log4J2. I've followed the guide at http://logging.apache.org/log4j/2.x/manual/customloglevels.html.

I need to create some unit test to verify that the events are being registered on their correct custom levels and configuration.

I appreciate any hint on how to start. Thanks a lot.


Solution

  • I recommend taking a look at the JUnit tests in log4j2.

    A number of log4j2 unit tests use a FileAppender with immediateFlush=true, then read in the file and check that some expected Strings exist in the output. Others configure a (org.apache.logging.log4j.test.appender.) ListAppender (this class lives in the core test jar) and obtain the LogEvent objects directly from the list.

    You may need to fork a new process for your log4j2 JUnit tests to make sure a different configuration has not already been loaded by some previous process.