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?
caplog
fixture, have you considered using it? Here is an answer with an example: stackoverflow.com/a/53161880/3800552. And here is the official documentation: docs.pytest.org/en/7.1.x/how-to/logging.html#caplog-fixture. No need to derive from unittest and do unittest style tests - do pytest test style instead.caplog
to no avail. The message gets logged with pytest format settings instead of the settings in my logging module. Would you be willing to contribute a full example?