Wednesday, October 5, 2016

Selenium Logging using Log4j and TestNG Reporter Logger

I am going to show couple of ways to perform logging using Log4j as well as TestNG Reporter.

Let's start with create new TestNG class 'LoggingDemo'. I am just writing single test to open amazon.com website and clicking on Account link.

Install log4j from http://logging.apache.org/log4j/2.x/index.html. I am using log4j 2 in this example.
After the download is complete, Add Log4j jar libraries to eclipse project just like we added selenium jars.


Initialize log4j and TestNG reporter log and I am going to use both in this class.

package automationFramework;

import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import org.apache.commons.logging.Log;
import org.apache.log4j.xml.DOMConfigurator;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.safari.SafariDriver;
import org.testng.Reporter;
import org.testng.annotations.Test;

public class LoggingDemo {
    private static WebDriver sDriver = new SafariDriver();
    private static Logger Log = Logger.getLogger(Log.class.getName());
   
  @Test
  public static void testOne() throws InterruptedException {
     
      Log.info("New driver has been initiated");
      DOMConfigurator.configure("log4j.xml");
      sDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
      Log.info("Implicit wait applied on the driver for 10 seconds");
      sDriver.get("http://amazon.com");
      Log.info("Web application launched");
     
      // Let's set TestNG reporter log now.
      Reporter.log("Application Lauched successfully....");
      sDriver.findElement(By.id("nav-link-yourAccount")).click();
      Log.info("Click action performed on My Account link");
      Thread.sleep(1000);
      sDriver.quit();
      Log.info("Browser closed");
     
      // This is the third main event
      Reporter.log("User is Logged out and Application is closed...");
  }
}


Log4j output will look like this in console -

Oct 05, 2016 11:54:57 AM automationFramework.LoggingDemo testOne
INFO: New driver has been initiated
Oct 05, 2016 11:54:57 AM automationFramework.LoggingDemo testOne
INFO: Implicit wait applied on the driver for 10 seconds
Oct 05, 2016 11:54:59 AM automationFramework.LoggingDemo testOne
INFO: Web application launched
Oct 05, 2016 11:54:59 AM automationFramework.LoggingDemo testOne
INFO: Click action performed on My Account link
Oct 05, 2016 11:55:00 AM automationFramework.LoggingDemo testOne
INFO: Browser closed

 
Now, Let's see TestNG Reporter log by going to output folder and click on 'Reporter output'


Log4J is low level logging whereas TestNG Reporter logger is high level logging.
 

No comments:

Post a Comment