Logging helps you see what your program is doing. Log4j makes logging easy and organized.
0
0
Logging with Log4j in Selenium Java
Introduction
You want to track what happens during Selenium tests.
You need to find errors or bugs by checking logs.
You want to save test results and messages for later review.
You want to control how much detail is shown in logs.
You want to write logs to a file or the console.
Syntax
Selenium Java
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class Example { private static final Logger logger = LogManager.getLogger(Example.class); public static void main(String[] args) { logger.info("This is an info message"); logger.error("This is an error message"); } }
Use LogManager.getLogger(ClassName.class) to create a logger.
Use different methods like info(), error(), debug() to log messages with levels.
Examples
Logs an informational message about starting a test.
Selenium Java
logger.info("Starting the test");Logs an error message when a test fails.
Selenium Java
logger.error("Test failed due to timeout");Logs a debug message showing a variable's value, useful for detailed troubleshooting.
Selenium Java
logger.debug("Value of variable x: " + x);Sample Program
This program logs messages at different levels during a simulated Selenium test. It shows info, debug, and error logs.
Selenium Java
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class SeleniumTestLogging { private static final Logger logger = LogManager.getLogger(SeleniumTestLogging.class); public static void main(String[] args) { logger.info("Test started"); try { // Simulate test steps logger.debug("Opening browser"); // Imagine Selenium code here logger.info("Navigating to homepage"); // Simulate error throw new Exception("Page not found"); } catch (Exception e) { logger.error("Test failed: " + e.getMessage()); } logger.info("Test finished"); } }
OutputSuccess
Important Notes
Make sure to add the Log4j library to your project dependencies.
Configure Log4j using a log4j2.xml or log4j2.properties file to control log format and destination.
Use appropriate log levels to avoid too much or too little information.
Summary
Log4j helps you keep track of what your Selenium tests do.
You create a logger and use it to write messages with different importance levels.
Proper logging helps find problems and understand test flow.