Logging function is used as a method for monitoring events in order to identify software issues as they occur.
While Pytest excels at executing tests, it doesn’t inherently showcase the results of print statements or logs, posing a challenge when diagnosing test failures.
So, what’s the remedy? How can we effectively log and observe events in real-time during our unit testing?
The solution lies in PyTest logging, offering the capability to generate and even modify log handlers within PyTest.
The file logger utilizes logging.FileHandler() to direct logs to a specified file. It’s also set to the INFO level, ensuring uniformity of logged information across the console and file outputs.
Below is an example of File Logger.
import logging
def test_logging_file():
# Create a named logger
logger = logging.getLogger(__name__)
# Create a file handler
filehandler = logging.FileHandler('logfile.log')
# Set the formatter for the file handler
formatter = logging.Formatter("%(asctime)s : %(levelname)s : %(name)s : %(message)s")
filehandler.setFormatter(formatter)
# Add the file handler to the logger
logger.addHandler(filehandler)
logger.setLevel(logging.INFO)
logger.debug("Debug statement is executed")
logger.info("Information statement is executed")
logger.warning("Warning mode, but test continues")
logger.error("Error has happened and failed the test")
logger.critical("Critical issue")
By default each captured log message shows the module, line number, log level and message.
If desired the log and date format can be specified to anything that the logging module supports by passing specific formatting options:
logging.Formatter("%(asctime)s : %(levelname)s : %(name)s : %(message)s")
![](https://qaautomation.expert/wp-content/uploads/2024/03/image-18.png?w=1200)
We can run the test by right clicking on the program and select Run ‘Python tests for test_logging_file’.
![](https://qaautomation.expert/wp-content/uploads/2024/03/image-16.png?w=444)
We can also run by using the below command in the terminal:
pytest test_logging_file.py -s
The output of the above program is
![](https://qaautomation.expert/wp-content/uploads/2024/03/image-19.png?w=1180)
The file is created in demo as the test file is there.
![](https://qaautomation.expert/wp-content/uploads/2024/03/image-20.png?w=355)
Below is an example of logfile.log.
![](https://qaautomation.expert/wp-content/uploads/2024/03/image-21.png?w=1119)
How to integrate logging in PyTest tests?
Let us create a BaseClass and mention the logging function there.
import inspect
import logging
class BaseClass:
def get_logger(self):
loggerName = inspect.stack()[1][3]
logger = logging.getLogger(loggerName)
filehandler = logging.FileHandler('logfile.log')
formatter = logging.Formatter("%(asctime)s : %(levelname)s : %(name)s : %(message)s")
filehandler.setFormatter(formatter)
logger.addHandler(filehandler)
logger.setLevel(logging.INFO)
return logger
We are creating a PyTest class that contains the test as will as will inherit the BaseClass.
import pytest
from demo.BaseClass import BaseClass
class TestExample3(BaseClass):
@pytest.fixture()
def dataload(self):
print("User Profile data")
return ["Vibha", "Singh", "qaautiomation.expert"]
@pytest.mark.usefixtures("dataload")
def test_user_profile(self, dataload):
log = self.get_logger()
log.info(dataload)
log.info(f'First Name : {dataload[0]}')
log.info(f'Surname : {dataload[1]}')
log.info(f'Website : {dataload[2]}')
Run the test using the below command:
pytest -s
The output of the above program is
![](https://qaautomation.expert/wp-content/uploads/2024/03/image-23.png?w=1080)
The output of the logfile.log is
![](https://qaautomation.expert/wp-content/uploads/2024/03/image-22.png?w=1140)
We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!