Why Use Logging in Selenium?

Logging is essential in Selenium automation for:
βœ”οΈ Debugging: Helps identify issues in test execution.
βœ”οΈ Tracking Execution: Records test steps and results.
βœ”οΈ Reporting: Provides test execution logs for analysis.
βœ”οΈ Better Maintenance: Helps in understanding failures over time.


Logging Methods in Selenium

βœ… Using System.out.println() (Basic Logging)

Using System.out.println() is the simplest way to log messages.

Example:

System.out.println("Test started...");

❌ Limitations:

  • No log levels (INFO, ERROR, DEBUG).
  • Difficult to track logs in large projects.
  • No file storage for logs.

βœ… Using Apache Log4j (Most Recommended)

Apache Log4j is a powerful logging framework that supports different log levels (INFO, DEBUG, ERROR, etc.).

Step 1: Add Log4j Dependency

For Maven projects, add this in pom.xml:

<dependencies>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.14.1</version>
    </dependency>
</dependencies>

Step 2: Create a Log4j Configuration File (log4j2.xml)

Save this in the resources folder.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5level - %msg%n" />
        </Console>
        <File name="File" fileName="logs/test.log">
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5level - %msg%n" />
        </File>
    </Appenders>
    <Loggers>
        <Root level="debug">
            <AppenderRef ref="Console" />
            <AppenderRef ref="File" />
        </Root>
    </Loggers>
</Configuration>

βœ… Logs are stored in logs/test.log.


Step 3: Implement Logging in Selenium Test

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.*;

public class Log4jTest {
    WebDriver driver;
    private static final Logger log = LogManager.getLogger(Log4jTest.class);

    @BeforeMethod
    public void setup() {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        driver = new ChromeDriver();
        log.info("Browser launched");
        driver.get("https://example.com");
        log.info("Navigated to website");
    }

    @Test
    public void testLogging() {
        try {
            WebElement element = driver.findElement(By.id("nonexistent"));
            element.click();
        } catch (NoSuchElementException e) {
            log.error("Element not found: " + e.getMessage());
        }
    }

    @AfterMethod
    public void teardown() {
        driver.quit();
        log.info("Browser closed");
    }
}

πŸ“Œ Log Levels Used:
βœ”οΈ log.info() β†’ General messages.
βœ”οΈ log.debug() β†’ Debugging info.
βœ”οΈ log.warn() β†’ Warnings.
βœ”οΈ log.error() β†’ Errors in execution.


βœ… Using Java’s Logger Class (Basic Alternative)

import java.util.logging.Logger;

public class JavaLoggerExample {
    private static final Logger logger = Logger.getLogger(JavaLoggerExample.class.getName());

    public static void main(String[] args) {
        logger.info("This is an info message");
        logger.warning("This is a warning");
    }
}

βœ… Pros: Simple, no external libraries required.
❌ Cons: Lacks advanced features like file logging.


βœ… Using Log4j with TestNG Reports

You can integrate Log4j logs into TestNG reports using ITestListener.

Step 1: Create a Listener Class

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.testng.ITestListener;
import org.testng.ITestResult;

public class TestNGListener implements ITestListener {
    private static final Logger log = LogManager.getLogger(TestNGListener.class);

    @Override
    public void onTestFailure(ITestResult result) {
        log.error("Test failed: " + result.getName());
    }

    @Override
    public void onTestSuccess(ITestResult result) {
        log.info("Test passed: " + result.getName());
    }
}

Step 2: Apply Listener to Test Class

import org.testng.annotations.*;

@Listeners(TestNGListener.class)
public class TestWithListener {
    @Test
    public void sampleTest() {
        System.out.println("Executing test...");
    }
}

βœ… Logs automatically appear in TestNG reports.


Conclusion

Logging Method
Features
Use Case
System.out.println()
Basic console output
Small projects
Java Logger
Basic logging with levels
Simple applications
Log4j βœ…
Advanced logging, supports files, integration with TestNG
Recommended for Selenium projects

πŸ”Ή Best Practice: Use Log4j with TestNG for scalable logging.