Skip to content

caplog

pytest also captures log records emitted via the standard logging module. By default:

  • Log messages are intercepted by pytest’s logging plugin.
  • Logs are not shown on the terminal unless a test fails or logging is explicitly configured.
  • Captured logs can be inspected during a test.

The caplog fixture lets you access and assert against captured log output:

python
import logging

def test_log_capture(caplog):
    logger = logging.getLogger("myapp")

    # Restrict capture to the "myapp" logger and include INFO-level records
    with caplog.at_level(logging.INFO, logger="myapp"):
        # Usually this is where you call a source function/method that logs internally.
        logger.warning("something happened")
        logger.info("End of execution")

    assert len(caplog.records) == 2
    assert caplog.records[0].levelname == "WARNING"
    assert caplog.records[0].message == "something happened"
    assert caplog.records[1].levelname == "INFO"
    assert caplog.records[1].message == "End of execution"