Logging helps you keep track of what your Selenium tests are doing. It records important events and errors so you can understand what happened during a test.
0
0
Logging setup in Selenium Python
Introduction
When you want to see what steps your Selenium test performed.
When you need to find out why a test failed by checking error messages.
When you want to save test results and events for later review.
When running tests on a remote machine and cannot watch the browser directly.
When debugging complex test flows to understand the sequence of actions.
Syntax
Selenium Python
import logging logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') logging.info('This is an info message') logging.error('This is an error message')
logging.basicConfig sets up the logging system with a level and format.
The level controls which messages are shown (INFO, ERROR, DEBUG, etc.).
Examples
This example shows how to log debug and info messages. Debug messages appear because the level is set to DEBUG.
Selenium Python
import logging logging.basicConfig(level=logging.DEBUG) logging.debug('Debug message') logging.info('Info message')
This example saves warning and error messages to a file named
test.log.Selenium Python
import logging logging.basicConfig(filename='test.log', level=logging.WARNING) logging.warning('Warning message') logging.error('Error message')
This example changes the log message format to show only the level and message.
Selenium Python
import logging logging.basicConfig(format='%(levelname)s: %(message)s') logging.info('Info message')
Sample Program
This program sets up logging to show info messages with timestamps. It runs a simple Selenium test that opens a website, finds a heading, logs the text, and handles errors.
Selenium Python
import logging from selenium import webdriver from selenium.webdriver.common.by import By logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') logging.info('Starting the Selenium test') # Setup Chrome driver options = webdriver.ChromeOptions() options.add_argument('--headless') driver = webdriver.Chrome(options=options) try: driver.get('https://example.com') logging.info('Opened example.com') element = driver.find_element(By.TAG_NAME, 'h1') logging.info(f'Found heading: {element.text}') except Exception as e: logging.error(f'Error during test: {e}') finally: driver.quit() logging.info('Closed the browser')
OutputSuccess
Important Notes
Use logging.error() to record problems that need attention.
Set the logging level to DEBUG for detailed messages during development.
Logging to a file helps keep records when running tests automatically.
Summary
Logging records important events and errors during Selenium tests.
Use logging.basicConfig() to set up logging level and format.
Logs help you understand test behavior and find problems quickly.