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:

   <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
      <version>2.0-beta8</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>2.0-beta8</version>
    </dependency>

Configuration

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"?>
<configuration>
  <appenders>
    <Console name="STDOUT" target="SYSTEM_OUT">
      <PatternLayout pattern="%d %-5p %F:%L - %m%n" />
    </Console>
  </appenders>
  <loggers>
    <logger name="org.apache.log4j.xml" level="info" />
    <root level="all">
      <appender-ref ref="STDOUT" />
    </root>
  </loggers>
</configuration>

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;

@Test
public class UsingLog4j {
  private static Logger log = LogManager
      .getLogger(UsingLog4j.class.getName());

  public void testLog4j() {
    log.info("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  DebugInformation.java:14 - Information message
2013-08-03 23:07:39,786 DEBUG DebugInformation.java:15 - Debug message
2013-08-03 23:07:39,786 DEBUG DebugInformation.java:16 - 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.