How to configure handling and formatting of log file in Selenium with python?

Selenium Web DriverAutomation TestingSoftware Testing

A log configuration consists of formatter and FileHandler methods. We need to import a logging package and then create an object which will be responsible for entire logging.

If we add the parameter _name_ inside the getLogger() method, we shall be able to add the test case name for which we want to create the log file. If this parameter is omitted in the argument, by default it prints root in the log file.


logger = logging.getLogger(_name_)

The different types of logger level are listed below. We can add all, some or at least one logger in our test case.

  • logger.debug("Debug log")
  •"Information log")
  • logger.warning("Warning log")
  • logger.error("Error log")
  • logger.critical("Critical log")

Then we should specify the location to the logger object to print these logs. This is handled with the help of addHandler() method. This method accepts the file handler object as its arguments.

The file handler object works with the parent logging package and its method known as the FileHandler(). This method contains the name and location of the log file where the entire logging information will be available.


fileHandler = logging.FileHandler('logfile.log')

Next we need to define the format in which the log file is to be created. This is achieved by the Formatter() method obtained from the parent logging package. The Formatter() method takes the format to be followed as an argument.


logging.Formatter("%(asctime)s :%(levelname)s : %(name)s :%(message)s")

This has to be stored in a formatter object and it can correlate with the fileHandler object via setFormatter() method. This method accepts the formatter object.



Finally, we need to set the level of logging. This is achieved by setLevel() method.



Through this we can limit printing of all types of logger levels in the log file.


Coding Implementation of logging configuration.

import logging
def loggingDmo():
# getLogger() method takes the test case name as input
logger = logging.getLogger(__name__)
# FileHandler() method takes location and path of log file
fileHandler = logging.FileHandler('logfile.log')
# Formatter() method takes care of the log file formatting
formatter = logging.Formatter("%(asctime)s :%(levelname)s :
%(name)s :%(message)s")
# addHandler() method takes fileHandler object as parameter
# setting the logger level
logger.debug("Debug log")"Information log ")
logger.warning("Warning log")
logger.error("Error log")
logger.critical("Critical log")
Published on 29-Jul-2020 14:27:17