How to test specific logging formatting in Python (using `pytest` and `unittest`)

Viewed 20

I am implementing a specific logging format, which is going to be parsed by another service for logging/monitoring/alerting purposes. Due to this, the logging format needs to be very specific.

I need to test that my application is indeed using the format I want. However, for whatever reason, pytest is using its own formatting and ignoring mine.

Reproducible example below:

# logtest.py
##### LOGGING CONFIGURATiON
import logging

LOG_CONFIG_FORMAT = '%(asctime)s {%(process)d-%(thread)d} %(levelname)s \
%(name)s@%(lineno)d my_field_1=%(my_field_1)s my_field_2=%(my_field_2)s my_field_3=\
%(my_field_3)s: %(message)s '

logging.basicConfig(level="DEBUG", format=LOG_CONFIG_FORMAT)


def get_logger(logger_name: str):
    logger = logging.getLogger(logger_name)
    adapter = logging.LoggerAdapter(logger, {
        'my_field_2': None,
        'my_field_1': None,
        'my_field_3': None
    })
    return adapter


##### APPLICATION CODE
logger = get_logger(__name__)


def my_func():
    for i in range(3):
        if i > 1:
            logger.extra = {
                'my_field_2': 'BOOM!!!',
                'my_field_1': 'BUST!!!',
                'my_field_3': 'CRASH!!!'
            }
        logger.debug(i)


##### EXECUTE APPLICATION FUNCTION
my_func()


##### TESTING CODE
import unittest


class TestCase(unittest.TestCase):

    def test_log(self):
        with self.assertLogs(level="DEBUG") as cm:
            my_func()
            print(cm.output)
            self.assertIn('my_field_1', cm.output[0])

If I execute python logtest.py I get the correct formatting. If I execute pytest logtest.py I get pytest's own formatting.

Not being concerned about pytest's console output, how can I test that the application logs are formatted indeed the way I want?

0 Answers
Related