Ekanto
Posted on May 29, 2022
Ever wondered running your selenium script but also thinking of saving the logs of every execution of your test cases? There is a much convenient way of doing this task in Selenium using Python. This article is all about this.
Main code
First of all, you need to create a python package, let's say it's name log. Inside of the package, create a python file (lets say it's logCapture.py). Then in this file, import a python package called logging. import logging
It should be included in the python when you install.
Then you can create a class and define method inside of it. It's better if you declare the method as a static method so that you can access the method from anywhere of your project without creating any objects of it's class. Then you can add the piece of code given below:
import logging
class LogGen:
@staticmethod
def loggen():
logger = logging.getLogger("Test Login")
fileHandler = logging.FileHandler('.\\YourDesiredFolderName')
formatter = logging.Formatter("%(asctime)s :%(levelname)s : %(name)s :%(message)s")
fileHandler.setFormatter(formatter)
logger.addHandler(fileHandler)
logger.setLevel(logging.INFO)
return logger
You can pass the name of your test case as a parameter inside the getLogger() method. The filehandler class will handle the your desired location for your logs. Formatter method will make sure your logs are being stored following a proper format. The logger variable will return the log at the end of the execution.
Driver code
Now it's time to use that loggen() function. Create another python file to add the driver code. Inside of this file, import the loggen function by simply using this code from log.logCapture import logGen
. The code is basically for accessing the LogGen class which we created earlier. Then use the logging by just calling the logger variable.
Let's say we want to test a login page. So you can add logs by using logger.info("You desired massage")
right before the execution of the test case or where ever you want. After executing the test cases, you will see a log file has been created in your desired folder. The log should look something like this
This is the output of my logs after executing the test cases. This is how my code looks like behind this
You should be able to use log if you follow this procedure :)
Thanks for reading. Pardon me for the mistakes I may have made as I am new to automation testing and still exploring everyday. I would be glad if it helps anyone. :)
Posted on May 29, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.