Creating Custom Test Logs in Selenium Python
Logging is a critical component of any test automation framework. It helps testers understand what happened during test execution, especially when tests fail. In Selenium Python, while you can rely on the default console output for quick debugging, creating custom test logs gives you more control, better organization, and improved visibility into your test runs.
In this blog, we’ll walk you through how to implement custom logging in your Selenium Python tests using Python’s built-in logging module, and show you best practices to make your logs readable, informative, and production-ready.
🧠 Why Custom Test Logs Matter
Here’s why custom logging is important in test automation:
Traceability: Track what steps were executed and in what order.
Debugging: Easier identification of failures or flaky tests.
Auditability: Logs act as records of test execution for compliance or reporting.
Integration: Useful for integrating with CI/CD pipelines and test reports.
🛠 Setting Up Logging in Selenium Python
Python’s logging module allows you to create configurable logs at different levels (DEBUG, INFO, WARNING, ERROR, CRITICAL). Let’s integrate it into a Selenium script.
1. Basic Logging Configuration
Start by setting up a logging configuration:
python
Copy
Edit
import logging
# Configure the logging
logging.basicConfig(
filename='test_log.log',
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s'
)
This creates a file named test_log.log and logs events with timestamps, levels, and messages.
2. Integrating Logging into Selenium Script
Here’s a simple Selenium test with custom logging:
python
Copy
Edit
from selenium import webdriver
from selenium.webdriver.common.by import By
import logging
# Configure logging
logging.basicConfig(
filename='test_log.log',
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
def test_google_search():
logging.info("Starting test: Google Search")
try:
driver = webdriver.Chrome()
logging.info("Browser launched successfully")
driver.get("https://www.google.com")
logging.info("Navigated to Google")
search_box = driver.find_element(By.NAME, "q")
logging.info("Search box found")
search_box.send_keys("Selenium Python")
logging.info("Entered search term")
search_box.submit()
logging.info("Submitted the search")
assert "Selenium Python" in driver.title
logging.info("Page title validated")
except Exception as e:
logging.error(f"Test failed due to: {str(e)}")
finally:
driver.quit()
logging.info("Browser closed")
test_google_search()
This script logs every major step, from launching the browser to submitting the search form and validating the page title.
✅ Best Practices for Custom Logging
Log Meaningful Information: Log actions like clicking buttons, navigating to URLs, and form submissions.
Use Log Levels Wisely:
DEBUG for detailed diagnostic output
INFO for general progress updates
ERROR for exceptions and failures
Avoid Over-Logging: Don't log every single WebDriver call. Focus on logical test steps.
Organize Logs by Test Case: Use separate log files for each test or include test names in log entries.
Add Screenshot Paths: Log screenshot file names when capturing images during failures.
📦 Bonus: Creating a Custom Logger Function
You can encapsulate your logging setup in a function or module for reuse:
python
Copy
Edit
def create_logger(name):
logger = logging.getLogger(name)
handler = logging.FileHandler(f"{name}.log")
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
return logger
Call this function in your tests to generate separate log files.
🧩 Final Thoughts
Custom logging in Selenium Python not only improves visibility into your test runs but also makes debugging significantly easier. With structured logs, you can quickly identify what failed, why it failed, and what happened before and after. By following best practices and leveraging Python’s logging module, you can build more maintainable and scalable automation frameworks.
Learn Selenium with Pyhton Training Hyderabad
Read More: Running Firefox in Headless Mode with Selenium Python
Read More: Headless Browser Testing in Selenium Python
Read More: Dockerizing Selenium Python Tests
Visit IHUB Talent Institute Hyderabad
Get Direction
Comments
Post a Comment