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):
| Level | Use Case |
|---|---|
ALL | Log everything |
TRACE | Very fine-grained debug info |
DEBUG | Debugging messages |
INFO | General execution info |
WARN | Potential issues, not errors |
ERROR | Errors that allow continuation |
FATAL | Severe errors — app may stop |
OFF | Disable 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
