Structured Logging in Selenium with Logback and SLF4J
When we are creating UI automation framework with selenium logging is the best way to understand and clarify issues. If we debug flaky tests or analyzing results in CI/CD pipelines, a clean logging setup can save hours of guesswork.
Logback is a tool that helps Java applications print useful messages (logs) during execution — such as errors, warnings, or info about what the app is doing — and can output these messages to the console, files, or other systems.
Logback is a modern logging framework for Java, considered the successor to Log4j. It’s fast, flexible, and works along with SLF4J (Simple Logging Facade for Java).In this post, we will see how to integrate
Logback, a modern logging framework for java, into Selenium automation framework.
Setting up Logback in a selenium Project
Step 1 : pom.xml Configuration
Add the dependencies for Logback and SLF4J, along with Selenium and any other required dependencies, to the pom.xml file.
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.9</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.4.14</version>
</dependency>Step 2 : Integrating Logback
Create a logback.xml file to define how log messages should be formatted and where they should be stored.
Place this file inside the src/test/resources directory of your project.
Here is a sample configuration of logback.xml
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss} %-5level - %msg%n</pattern>
</encoder>
</appender>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>logs/application.log</file>
<append>true</append>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss} %-5level - %msg%n</pattern>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE" />
</root>
</configuration>
Appender in logback
Appender is a component that handles the actual process of logging the messages to various destinations. Different types of appenders allow you to write logs to different outputs like the console and files or even databases.
Here are the most common types of appenders you can use in logback.xml
ConsoleAppender: The ConsoleAppender in Logback is used to output log messages into the console. It's extremely useful during development, testing, and debugging to immediately see what your application is doing.
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss} %-5level - %msg%n</pattern>
</encoder>
</appender>
FileAppender : The FileAppender in Logback writes log messages to a file on the system's disk, making it ideal for persistent logging. This allows you to retain logs over time for future analysis. You can configure it to either append new log entries to the file or overwrite the file each time the application starts.
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>logs/application.log</file>
<append>true</append>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss} %-5level - %msg%n</pattern>
</encoder>
</appender>Logback Pattern Encoder
In Logback, the encoder defines the format of log messages before they are written to the output, such as the console or a file. The pattern set within the encoder determines the structure and content of each log entry.
A sample encoder pattern
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss} %-5level - %msg%n</pattern>
</encoder>Logback Encoder Pattern Explanation:
This is the basic format of each log line in console and log file. The <encoder> element in a Logback configuration file is responsible for formatting log messages before they are output to a particular appender (e.g., console, file).
Let us see each component used in the above said format.
%d{yyyy-MM-dd HH:mm:ss} : Date/Time of the Log Entry
%d indicates the date and time when the log messages were created.
{yyyy-MM-dd HH:mm:ss}: This is the format for the date and time.
This helps you trace when the log message was generated.
%-5level : Log Level
This part controls the log level of the message (e.g. INFO,ERROR,DEBUG,WARN,TRACE).
The -5 means the log level will be left-aligned within a 5-character wide field. If the log level has fewer than 5 characters (e.g., INFO), it will be padded with spaces on the right to maintain the 5-character width.
- %msg : Log Message.
This part represents the log message itself.
%msg refers to the actual log content or message that you are logging, which will be the primary content of the log entry (e.g., "Test started", "Error occurred", etc.).
%n – New Line
This inserts a new line at the end of each log message, ensuring that each log entry appears on a new line in the output.
Root Element in Logback Configuration
The <root> element in Logback defines the default logging level for your application and assigns appenders that determine the output destination and format of log messages, such as the console or a log file.
<root level="debug">
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE" />
</root><root level="debug"> - This sets the default log level for the application to debug
This means that all log messages with a level of debug, info, warn, and error will be captured, but messages with a level lower than debug (like trace) will be ignored.
<appender-ref ref="STDOUT" /> - this refers to the console appender where Logs will show in terminal
<appender-ref ref="FILE" /> - this refers to the file appender, which writes log messages to the file specified in the FileAppender configuration, in this case, logs/application.log.
Logging Levels
Logging levels are priorities assigned to log messages. The logging levels are from lowest to highest as follows
TRACE-->DEBUG-->INFO-->WARN-->ERROR.
Step 3 : Add Logging to a class
Sample Java class with logback integration
package logback;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SeleniumLogExample {
private static final Logger logger = LoggerFactory.getLogger(SeleniumLogExample.class);
public static void main(String[] args) {
logger.info("Test started");
WebDriver driver = new FirefoxDriver();
logger.info("WebDriver: Firefox Driver");
logger.info("Navigating to google.com");
driver.get("https://www.google.com/");
logger.debug("Page title is: {}", driver.getTitle());
try {
throw new Exception(" Simulate error!");
} catch (Exception e) {
logger.error("Error: " + e.getMessage());
}
driver.quit();
logger.info("Test finished");
}
}
Output at console will look like below.

Output at application.log file will look like below.

Advantages of logback over log4j
Logback, designed as a successor to Log4j, offers several advantages that make it a more efficient and flexible logging framework.
Performance and Efficiency: Logback is generally faster and more memory-efficient than Log4j. It also handles asynchronous logging more effectively, improving overall performance.
Integration with SLF4J:Logback integrates natively with SLF4J, but Log4j, which requires adapters. SLF4J enables easy switching between different logging backends (such as Logback, Log4j, etc.) without modifying application code, ensuring it remains decoupled from the specific logging implementation.
Advanced Rolling Policies: Logback has built-in support for both time-based and size-based rolling policies, allowing you to manage log files more effectively.
Flexible Configuration: Logback provides conditional configuration using the <if> tag, making it easy to define variables, profiles, and external property files in the logback.xml. It also supports automatic reloading of configuration files without the need to restart the application.
Enhanced Built-In Features: Logback includes features like log file compression, email notifications for critical logs, log filtering based on conditions, and the ability to color console logs for better readability.
Cleaner and More Readable Configuration: The logback.xml configuration file is generally cleaner and easier to read compared to Log4j’s older .properties or XML formats, making configuration simpler and more maintainable.
Conclusion
By integrating Logback with SLF4J and Selenium, you can greatly improve the maintainability and transparency of your automated web tests. With the right configuration, logs will provide valuable insights during test execution, making it easier to debug and optimize your tests. Whether you're running tests on your local machine or in a continuous integration environment, having effective logging in place is key to ensuring smooth test execution and providing valuable information for future improvements.
Thanks for reading the blog! Hope you found it helpful—happy learning and best of luck on your coding journey!


