Sub topic 14
Testing log output with assertLogs
This chapter assumes you know the logger hierarchy, log levels, and basic unittest test classes. Log messages are part of a program's observable behavior. Operators rely on them, so a test can check that a warning was emitted when something went wrong. The standard library provides TestCase.assertLogs for this.
What assertLogs does
assertLogs(logger=None, level=None) is a context manager. While the block runs, it temporarily replaces the handlers on the chosen logger with a capturing handler. When the block exits, it fails the test if no record at or above level was emitted.
loggercan be a logger object or a name. If omitted, it uses the root logger.levelcan be a number or a name such as"WARNING". If omitted, it usesINFO.- The captured records are available in the object bound by
as.
A worked example
import logging
import unittest
logger = logging.getLogger("myapp.billing")
def charge(amount):
if amount <= 0:
logger.warning("Rejected charge of %s", amount)
return False
logger.info("Charged %s", amount)
return True
class ChargeTest(unittest.TestCase):
def test_rejects_negative_amount(self):
with self.assertLogs("myapp", level="WARNING") as cm:
result = charge(-5)
self.assertFalse(result)
self.assertEqual(cm.output, ["WARNING:myapp.billing:Rejected charge of -5"])
self.assertEqual(cm.records[0].levelname, "WARNING")
def test_valid_charge_logs_nothing_at_warning(self):
with self.assertNoLogs("myapp", level="WARNING"):
charge(10)
if __name__ == "__main__":
unittest.main()The test watches "myapp", but the code logs to "myapp.billing". This works because the record propagates up to the parent logger, where the capturing handler sits.
Reading the results
| Attribute | Contents |
|---|---|
| `cm.output` | A list of strings formatted as `LEVEL:logger_name:message` |
| `cm.records` | The `LogRecord` objects, useful for checking `levelname`, `args`, or `exc_info` |
Use cm.output for quick equality checks. Use cm.records when you need structured fields, such as confirming that an exception was attached.
assertNoLogs is available from Python 3.10. It fails if any record at or above the level is emitted.
Common errors
- Wrong logger name. Watching
"myapp.db"will not capture a record sent to"myapp.billing". Siblings do not share records, but a parent captures its children. - Level too high.
level="ERROR"ignores warnings, so the assertion fails with "no logs of level ERROR or higher triggered". - Output sent elsewhere. While the block runs, handlers on the watched logger are replaced and propagation is turned off. Other tests should not depend on that logger's real handlers during the block.
- Comparing the unformatted message.
cm.outputcontains the final formatted text. Compare"Rejected charge of -5", not the template"Rejected charge of %s".
Exercise
A function logs logger.info("cache miss") on the logger "shop.cache". Your test uses with self.assertLogs("shop", level="WARNING"): around a call to that function. Does the test pass? Why, and what is the smallest fix if you want it to pass?
Show answer
The test fails. The record does reach the "shop" logger through propagation, but it is at INFO, which is below the WARNING threshold, so nothing is captured and assertLogs raises an AssertionError. The smallest fix is to change the level to "INFO" (or omit it, since INFO is the default).