How to Use caplog in pytest for Logging Assertions
Use the
caplog fixture in pytest to capture log messages during test runs. Access caplog.records or caplog.text to assert log content and verify logging behavior in your tests.Syntax
The caplog fixture is passed as a parameter to your test function. You can then access:
caplog.records: a list of log records captured during the test.caplog.text: a string of all captured log messages.caplog.set_level(level): to set the logging level for capturing logs.
python
def test_example(caplog): caplog.set_level("INFO") # Your code that logs messages assert "expected log" in caplog.text
Example
This example shows how to capture and assert log messages using caplog. It sets the log level to INFO, triggers a log, and checks if the message was captured.
python
import logging def function_to_test(): logging.info("This is an info log message.") def test_logging(caplog): caplog.set_level(logging.INFO) function_to_test() assert any("info log message" in record.message for record in caplog.records) assert "info log message" in caplog.text
Output
============================= test session starts =============================
collected 1 item
test_logging.py . [100%]
============================== 1 passed in 0.01s ==============================
Common Pitfalls
- Not setting the log level with
caplog.set_level()can cause logs below the default level to be missed. - Checking
caplog.textwithout considering log levels may lead to false negatives. - Using
caplog.recordsrequires checking themessageattribute, not the record itself.
python
import logging def test_wrong_usage(caplog): # Logs at DEBUG level won't be captured by default logging.debug("Debug message") assert "Debug message" not in caplog.text # This will pass because DEBUG is ignored def test_correct_usage(caplog): caplog.set_level(logging.DEBUG) logging.debug("Debug message") assert "Debug message" in caplog.text # Correctly captures DEBUG logs
Quick Reference
| caplog Feature | Description |
|---|---|
| caplog.set_level(level) | Set the minimum log level to capture (e.g., INFO, DEBUG) |
| caplog.records | List of captured log records with detailed info |
| caplog.text | All captured log messages as a single string |
| Use in test function parameter | Add caplog as a test argument to enable capturing |
Key Takeaways
Pass
caplog as a parameter to your pytest test function to capture logs.Use
caplog.set_level() to control which log levels are captured.Check
caplog.records or caplog.text to assert log messages.Remember that logs below the set level are not captured by default.
Use
caplog to verify logging behavior without changing production code.