Introduction
When automation tests are executed, it is important to know what happened during each step of the execution. Simply knowing whether a test passed or failed is often not enough to diagnose issues. Testers need detailed information such as when the browser was launched, which page was opened, what actions were performed, and where the test failed.
The Python Logging Module is the built-in logging library in Python that records messages during program execution. Instead of using multiple print() statements, logging provides structured and configurable messages that help testers monitor test execution and troubleshoot failures.
In Selenium automation frameworks, logging is commonly used to record browser actions, test execution steps, exceptions, API responses, and other important events. These logs are extremely useful when debugging failed test cases or analyzing execution history.
In this tutorial, you’ll learn what the Python Logging Module is, why it is used, different logging levels, and how to use it in Selenium with Python.
What is the Python Logging Module?
logging is Python’s built-in module used to generate structured log messages during program execution.
Instead of printing information to the console using print(), the logging module records messages with different severity levels.
Common logging levels include:
DEBUG
INFO
WARNING
ERROR
CRITICAL
These log messages help testers understand what happened during test execution.
Why Use the Python Logging Module?
Using the Python Logging Module provides several benefits:
Records execution steps.
Simplifies debugging.
Tracks application behavior.
Captures error information.
Produces structured logs.
Supports different logging levels.
Can save logs to files.
Integrates easily with Selenium frameworks.
Logging Levels
The Python Logging Module provides the following logging levels:
| Logging Level | Description |
|---|---|
DEBUG | Detailed information used during development and debugging. |
INFO | General execution information such as browser launch or page navigation. |
WARNING | Indicates a potential issue that does not stop execution. |
ERROR | Records an error that affects the current operation. |
CRITICAL | Indicates a serious error that may stop the application or test execution. |
Example
import logging
from selenium import webdriver
def test_python_logging_module():
logging.basicConfig(
level=logging.INFO,
format="%(levelname)s: %(message)s"
)
logger = logging.getLogger("selenium")
driver = webdriver.Chrome()
try:
logger.info("Launching browser")
driver.get(
"https://www.testmuai.com/selenium-playground/"
)
logger.info(
"Opened %s",
driver.current_url
)
assert "selenium-playground" in driver.current_url
finally:
driver.quit()
Understanding the Code
Import Required Modules
import logging
from selenium import webdriver
The required modules are imported.
loggingis Python’s built-in module used to generate log messages.webdriveris used to launch and control the browser.
Configure Logging
logging.basicConfig(
level=logging.INFO,
format="%(levelname)s: %(message)s"
)
The basicConfig() method configures the logging system.
In this example:
level=logging.INFOdisplays INFO messages and higher severity levels.format="%(levelname)s: %(message)s"specifies how each log message will appear.
Example output:
INFO: Launching browser
INFO: Opened https://www.testmuai.com/selenium-playground/
Create a Logger
logger = logging.getLogger("selenium")
A logger named selenium is created.
This logger is responsible for generating log messages throughout the test.
Launch the Browser
driver = webdriver.Chrome()
A new Chrome browser instance is created.
Log Browser Launch
logger.info("Launching browser")
An INFO-level message is written to the log before opening the application.
This helps track when the browser was launched.
Open the Application
driver.get(
"https://www.testmuai.com/selenium-playground/"
)
The Selenium Playground application is opened.
Log the Current URL
logger.info(
"Opened %s",
driver.current_url
)
Another INFO message records the URL of the page that was opened.
The %s placeholder is replaced with the value of driver.current_url.
Example output:
INFO: Opened https://www.testmuai.com/selenium-playground/
Verify the Page
assert "selenium-playground" in driver.current_url
The assertion verifies that the browser successfully navigated to the expected page.
Close the Browser
finally:
driver.quit()
The browser is closed after the test execution.
Logging to a File
Instead of displaying logs only in the console, they can also be saved to a file.
Example:
logging.basicConfig(
filename="automation.log",
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s"
)
This creates a log file named automation.log containing all log messages.
Practical Example
Suppose an e-commerce application contains hundreds of Selenium test cases.
During execution, the framework logs browser launches, user login attempts, product searches, and checkout operations. If a test fails, the log file helps identify exactly where the failure occurred.
Automation Testing Example
Consider an online banking application.
The automation framework logs customer login, account selection, fund transfer, and logout operations. If a transfer fails, the logs provide detailed execution information, helping QA engineers and developers quickly determine the root cause.
Real-World Example
The Python Logging Module is widely used in:
Selenium Automation Frameworks
API Automation Frameworks
PyTest Frameworks
CI/CD Pipelines
Banking Applications
Healthcare Systems
E-commerce Platforms
Enterprise Automation Projects
Logging is an essential part of professional automation frameworks because it provides a detailed record of test execution.
Advantages of the Python Logging Module
Produces structured log messages.
Improves debugging.
Records execution history.
Supports multiple logging levels.
Can save logs to files.
Helps identify failures quickly.
Integrates easily with Selenium.
Supports large automation projects.
Common Mistakes Beginners Make
Using print() Instead of Logging
Avoid relying on print() statements for automation frameworks.
Use the logging module because it provides structured and configurable log messages.
Logging Too Much Information
Avoid excessive logging that makes the log files difficult to read.
Log only meaningful execution details.
Using Only One Logging Level
Use different logging levels appropriately based on the importance of the message.
Ignoring Log Files
Always review log files when investigating failed test cases.
Best Practices
Use the logging module instead of
print().Configure logging at the beginning of the framework.
Use appropriate logging levels.
Save logs to files for future reference.
Include timestamps in log messages.
Log important Selenium actions.
Combine logging with screenshots and reports for effective debugging.
Conclusion
The Python Logging Module is a powerful built-in library for recording structured messages during Selenium automation. It helps testers monitor execution, identify failures, and troubleshoot issues efficiently by generating meaningful log messages. Because of its flexibility, support for multiple logging levels, and ability to write logs to files, the Python Logging Module is a standard component of professional Selenium automation frameworks.
Frequently Asked Questions (FAQs)
What is the Python Logging Module?
The Python Logging Module is a built-in library used to generate structured log messages during program execution.
Why is logging important in Selenium automation?
Logging records important execution details, making it easier to debug failed test cases and analyze automation runs.
What are the common logging levels?
The common logging levels are:
DEBUGINFOWARNINGERRORCRITICAL
Can Python save log messages to a file?
Yes.
The logging module can write log messages to a file using the filename parameter in logging.basicConfig().
Is the Python Logging Module used in professional automation frameworks?
Yes.
The Python Logging Module is widely used in professional Selenium automation frameworks to record execution steps, browser actions, errors, and debugging information, making test execution easier to analyze and maintain.
Key Takeaways
loggingis Python’s built-in module for generating structured log messages.It supports multiple logging levels such as
DEBUG,INFO,WARNING,ERROR, andCRITICAL.Logging improves debugging by recording execution details.
Logs can be displayed in the console or saved to files.
The Python Logging Module is a standard utility in professional Selenium automation frameworks.
