0
0
PyTesttesting~5 mins

Log level filtering in PyTest

Choose your learning style9 modes available
Introduction

Log level filtering helps you see only the important messages when tests run. It keeps logs clear and easy to understand.

When you want to ignore debug messages and see only warnings or errors.
When you need to find why a test failed by focusing on error logs.
When running many tests and want to reduce clutter in the log output.
When sharing test results with teammates and want to highlight important logs.
Syntax
PyTest
import logging

def test_example(caplog):
    with caplog.at_level(logging.WARNING):
        logging.debug('Debug message')
        logging.warning('Warning message')
        logging.error('Error message')
    assert 'Warning message' in caplog.text
    assert 'Debug message' not in caplog.text

Use caplog.at_level() to set the log level inside a test.

Only messages at or above the set level will be captured.

Examples
Only error messages are captured, warnings are ignored.
PyTest
with caplog.at_level(logging.ERROR):
    logging.warning('This will not show')
    logging.error('This will show')
All messages from debug and above are captured.
PyTest
with caplog.at_level(logging.DEBUG):
    logging.debug('Debug info')
    logging.info('Info message')
Sample Program

This test sets the log level to WARNING. It checks that only warning and error messages are captured. Debug and info messages are ignored.

PyTest
import logging

def test_log_filtering(caplog):
    with caplog.at_level(logging.WARNING):
        logging.debug('Debug message')
        logging.info('Info message')
        logging.warning('Warning message')
        logging.error('Error message')

    assert 'Warning message' in caplog.text
    assert 'Error message' in caplog.text
    assert 'Debug message' not in caplog.text
    assert 'Info message' not in caplog.text

    print('Captured logs:')
    print(caplog.text)
OutputSuccess
Important Notes

Use caplog.text to get all captured log messages as a string.

Log levels from lowest to highest: DEBUG, INFO, WARNING, ERROR, CRITICAL.

Setting a higher log level filters out lower priority messages.

Summary

Log level filtering helps focus on important log messages during tests.

Use caplog.at_level() to set the desired log level in pytest.

Only messages at or above the set level appear in the captured logs.