TestNG - Custom Logging


We had earlier read about the different options that TestNG provides for logging and reporting. Now, let's learn how to start using them. To start with, we will write a sample program in which we will use the ITestListener interface for logging purposes.

Create Test Case Class

Create a java class, say, SampleTest.java in /work/testng/src.

import org.testng.Assert;
import org.testng.annotations.Test;

public class SampleTest {
   public void testMethodOne() {

   public void testMethodTwo() {

   public void testMethodThree() {

The preceding test class contains three test methods out of which testMethodOne and testMethodThree will pass when executed, whereas testMethodTwo is made to fail by passing a false Boolean value to the Assert.assertTrue method, which is used for truth conditions in the tests.

Create Custom Logging Class

Create another new class named CustomListener.java in /work/testng/src.

import org.testng.ITestResult;
import org.testng.TestListenerAdapter;

public class CustomListener extends TestListenerAdapter{
   private int m_count = 0;

   public void onTestFailure(ITestResult tr) {
      log(tr.getName()+ "--Test method failed\n");

   public void onTestSkipped(ITestResult tr) {
      log(tr.getName()+ "--Test method skipped\n");

   public void onTestSuccess(ITestResult tr) {
      log(tr.getName()+ "--Test method success\n");

   private void log(String string) {
      if (++m_count % 40 == 0) {


The above class extends TestListenerAdapter, which implements ITestListener with empty methods. Hence, no need to override other methods from the interface. You can implement the interface directly, if you prefer so.

Create testng.xml

Create testng.xml in /work/testng/src to execute test case(s).

<?xml version = "1.0" encoding = "UTF-8"?>
<suite name = "Simple Logger Suite">
      <listener class-name = "CustomListener" />

   <test name = "Simple Logger test">
         <class name = "SampleTest" />

Compile the SampleTest, CustomListener classes using javac.

/work/testng/src$ javac CustomListener.java SampleTest.java

Now, run the testng.xml.

/work/testng/src$ java org.testng.TestNG testng.xml

Verify the output.

testMethodOne--Test method success
testMethodTwo--Test method failed
testMethodThree--Test method skipped

Simple Logger Suite
Total tests run: 3, Failures: 1, Skips: 1

We created a custom logger class, which implements the ITestListener interface and attached itself to the TestNG test suite as a listener. Methods of this listener class are invoked by TestNG when test started, at test fail, at test success, and so on. Multiple listeners can be implemented and added to the test suite execution, TestNG will invoke all the listeners that are attached to the test suite.

Logging listeners are mainly used when we need to see the continuous status of the test execution when the tests are getting executed.