Add logging to your test

We can implement a flexible logging system, called log4j. With log4j we can make use of six levels of logging. Every log level can be treated differently. We can make the following distinction between log levels: trace(), debug(), info(), warn(), error(), fatal()

In practice

We need to add two dependencies to our maven pom.xml file. Then we need to create a log4j2.xml file in our classpath containing the logging configuration. After this we are able to use the flexible logging system.

Maven dependency

Open the POM.xml file and add the following XML snippet between the <dependencies></dependencies> tags:



We can filter the logging output by setting the root level log level. These are the log levels (specified in order): all, trace, debug, info, warn, error, fatal and off. They have the following meaning: all will output all the log level messages and info will output the information log level messages and above (info, warn, error, fatal). The same principle applies for the other log levels.

<?xml version="1.0" encoding="UTF-8"?>
    <Console name="STDOUT" target="SYSTEM_OUT">
      <PatternLayout pattern="%d %-5p %F:%L - %m%n" />
    <logger name="org.apache.log4j.xml" level="info" />
    <root level="all">
      <appender-ref ref="STDOUT" />

Using the logger

We have to define a static reference variable to a Logger instance returned by the .getlogger method of the LogManager class. This instance will get a reference name as the class in which it will be used.

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.testng.annotations.Test;

public class UsingLog4j {
  private static Logger log = LogManager

  public void testLog4j() {"Information message");
    log.debug("Debug message");
    log.error("Error message");

Logging output

The following log4j output is configured with root level all, displaying all the log level messages.

2013-08-03 23:07:39,784 INFO - Information message
2013-08-03 23:07:39,786 DEBUG - Debug message
2013-08-03 23:07:39,786 DEBUG - Error message

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.