'How to log error messages in the text file using selenium python

I am using pytest framework for automation a website. I have written the below code for logging the errors but this code only captures execution steps of the automation scripts like below

Logfile Example

2022-04-20 14:35:45,015 - BasePage.py:[27] - [INFO] - Clicking on an Element health_XPATH

Loggin Code:

import logging
import time
from Utilities.filepath import *


class Logger():

    def __init__(self, logger, file_level=logging.INFO):
        self.logger = logging.getLogger(logger)
        self.logger.setLevel(logging.DEBUG)

        fmt = logging.Formatter('%(asctime)s -'
                                ' %(filename)s:[%(lineno)s] - [%(levelname)s] - %(message)s')

        curr_time = time.strftime("%Y-%m-%d")
        # self.LogFileName = 'C:\\Users\\aprat\\PycharmProjects\\Regression-Web-Automation\Logs\\log' + curr_time + '.txt'
        self.LogFileName = FilePath.logfile_path + curr_time + '.txt'

        fh = logging.FileHandler(self.LogFileName, mode="a")
        fh.setFormatter(fmt)
        fh.setLevel(file_level)
        self.logger.addHandler(fh)

Now for any error occurs in case of any failures or script issues, that error message is not getting captured in the log(text file). The error message is only can be seen from the console.

My goal is to capture all the execution steps as I have mentioned above and also the error messages like "element not found" or "stale element exception" etc.



Solution 1:[1]

What about using loguru instead?. it is pretty much out of the box

you can catch easily exceptions (from loguru examples)

@logger.catch
def my_function(x, y, z):
    # An error? It's caught anyway!
    return 1 / (x + y + z)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1