Pytest Logging to print to Console

HOME

import logging


def test_logging_console():
    logger = logging.getLogger(__name__)

    # Create a console handler
    console_handler = logging.StreamHandler()

    # Set the formatter for the console handler
    formatter = logging.Formatter("%(asctime)s : %(levelname)s : %(name)s : %(message)s")
    console_handler.setFormatter(formatter)

    # Add the console handler to the logger
    logger.addHandler(console_handler)
    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")

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

pytest test_logging_console.py -s

Leave a comment