</>

Technology

Selenium

Difficulty

Intermediate

Interview Question

Name an API used for logging in Java automation.

Log4j is the most popular open-source logging API in Java. It supports multiple log levels: ALL, DEBUG, INFO, WARN, ERROR, TRACE, and FATAL.

Answer

Logging API in Java — Log4j

Log4j (Log for Java) is an open-source logging framework maintained by Apache. It is the most widely used logging API in Java Selenium automation projects.

Log levels (in order of severity):

LevelUse Case
ALLLog everything
TRACEVery fine-grained debug info
DEBUGDebugging messages
INFOGeneral execution info
WARNPotential issues, not errors
ERRORErrors that allow continuation
FATALSevere errors — app may stop
OFFDisable all logging

Maven dependency (Log4j 2):

XML
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.20.0</version>
</dependency>

Basic usage in Selenium test:

Java
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class LoginTest {

    private static final Logger log = LogManager.getLogger(LoginTest.class);

    @Test
    public void loginTest() {
        log.info("Starting login test");
        log.debug("Navigating to URL: https://example.com");
        driver.get("https://example.com");

        try {
            driver.findElement(By.id("username")).sendKeys("admin");
            log.info("Entered username successfully");
        } catch (Exception e) {
            log.error("Failed to enter username: " + e.getMessage());
        }

        log.info("Login test completed");
    }
}

log4j2.xml configuration:

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

Key benefits:

  • Logs execution flow for debugging failed tests
  • Multiple output destinations (console, file, database)
  • Configurable log levels — filter noise in CI environments
  • Thread-safe for parallel test execution

Follow AutomateQA

Related Topics