Sub topic 14
Testing log output with assertLogs
This chapter assumes you know the logger hierarchy, levels, and handlers from earlier chapters, and that you can write a basic unittest.TestCase. It shows how to check that your code logs what it should, without reading log files or patching print.
Why test logging at all
Log messages are often the only record of a rejected payment, a retry, or a swallowed exception. If a refactor removes a logger.warning call, nothing fails and nobody notices until an incident. A test that pins the important messages catches that early.
Test the events that matter to operators, such as warnings, errors, and state changes. Do not test every debug line.
What assertLogs does
TestCase.assertLogs(logger=None, level=None) is a context manager. Its arguments are:
loggeris a logger name or aLoggerobject. If you omit it, the root logger is used.levelis a level name or number. If you omit it,INFOis used.
The block must cause at least one record at that level or higher to reach the named logger, either directly or from one of its children. Otherwise the test fails with an AssertionError.
The object returned by with ... as cm has two lists:
cm.outputholds the formatted lines, in the formLEVEL:logger_name:message.cm.recordsholds theLogRecordobjects, so you can checklevelno,args,exc_info, and other attributes.
What happens inside the block
On entry, assertLogs swaps out the logger's state. On exit, it puts everything back.
Two consequences follow:
- The logger's own handlers are removed during the block, and
propagateisFalse. Records do not reach the console, files, or the root logger, so the test run stays quiet. - The capturing handler is attached directly, so the test does not depend on your application's logging configuration. A library that only has a
NullHandlercan be tested the same way.
A complete example
This file defines two small functions that log and a test case that checks them. Save it as test_billing.py and run python -m unittest test_billing.
import logging
import unittest
logger = logging.getLogger("myapp.billing")
def charge(amount):
if amount <= 0:
logger.warning("Rejected non-positive amount %s", amount)
return False
logger.info("Charged %s", amount)
return True
def parse_amount(text):
try:
return int(text)
except ValueError:
logger.exception("Could not parse %r", text)
return None
class BillingLogTest(unittest.TestCase):
def test_rejects_zero(self):
with self.assertLogs("myapp", level="WARNING") as cm:
result = charge(0)
self.assertFalse(result)
self.assertEqual(
cm.output,
["WARNING:myapp.billing:Rejected non-positive amount 0"],
)
def test_info_is_captured_by_default_level(self):
with self.assertLogs("myapp") as cm:
charge(5)
self.assertEqual(cm.output, ["INFO:myapp.billing:Charged 5"])
def test_record_attributes(self):
with self.assertLogs("myapp.billing", level="WARNING") as cm:
charge(-1)
record = cm.records[0]
self.assertEqual(record.levelno, logging.WARNING)
self.assertEqual(record.args, (-1,))
self.assertEqual(record.name, "myapp.billing")
def test_exception_is_logged_with_traceback(self):
with self.assertLogs("myapp", level="ERROR") as cm:
self.assertIsNone(parse_amount("abc"))
exc_type = cm.records[0].exc_info[0]
self.assertIs(exc_type, ValueError)
def test_failure_when_nothing_is_logged(self):
with self.assertRaises(AssertionError):
with self.assertLogs("myapp", level="WARNING"):
charge(10)
if __name__ == "__main__":
unittest.main()The first test passes "myapp" rather than "myapp.billing". Because myapp.billing is a child, its records propagate up to myapp and are captured there. Naming a parent logger is a good default, since the test keeps working if the code moves to a different child logger.
Choosing what to assert on
You can check the formatted line, the record, or just a fragment of the message. The right choice depends on how stable the message is.
| Assertion target | Good for | Risk |
|---|---|---|
| `cm.output == [...]` | Short, stable messages | Breaks on any wording change |
| `assertIn("text", cm.output[0])` | Checking one key fact | Can pass on the wrong record |
| `cm.records[i].levelno` | Checking severity | Does not check the text |
| `cm.records[i].args` | Checking the values logged | Depends on lazy `%s` style calls |
| `cm.records[i].exc_info` | Checking that a traceback was attached | None significant |
Because you log with logger.info("Charged %s", amount) instead of f-strings, record.args keeps the values separate from the text. You can then assert on the data without matching the wording.
When the output contains an exception, each string in cm.output also contains the formatted traceback. Exact comparison is awkward in that case, so assert on exc_info instead.
Asserting that nothing is logged
Python 3.10 added assertNoLogs, which takes the same arguments and fails if any matching record is emitted.
import logging
import unittest
logger = logging.getLogger("myapp.cache")
def lookup(cache, key):
if key in cache:
return cache[key]
logger.debug("miss for %s", key)
return None
class QuietTest(unittest.TestCase):
def test_hit_logs_nothing(self):
with self.assertNoLogs("myapp", level="DEBUG"):
lookup({"a": 1}, "a")
def test_miss_logs_debug_only(self):
with self.assertLogs("myapp", level="DEBUG") as cm:
lookup({}, "a")
self.assertEqual(cm.output, ["DEBUG:myapp.cache:miss for a"])
with self.assertNoLogs("myapp", level="INFO"):
lookup({}, "b")
if __name__ == "__main__":
unittest.main()The level is a floor, not an exact match. assertNoLogs("myapp", level="INFO") fails on a warning too, and passes if only DEBUG records appear. On Python 3.9 or earlier, you can emulate it by checking that assertLogs raises, but that is clumsy. Upgrading is better.
Common pitfalls
- Wrong logger name.
assertLogs("myapps")captures nothing, because the name does not match the code's logger. The test fails with "no logs of level ... triggered on myapps". Use__name__in the code and a parent prefix in the test. - Level too high.
assertLogsonly counts records at or abovelevel. To check a debug message, passlevel="DEBUG". The default isINFO. - Disabled loggers. If a test calls
logging.disable(logging.CRITICAL)or loads adictConfigwithoutdisable_existing_loggers: False, loggers can be switched off.assertLogsthen fails even though the code is correct. Undo the disabling intearDown. - Expecting output elsewhere. Inside the block, records are not propagated beyond the captured logger. Do not combine
assertLogswith checks on a console handler or log file for the same logger. - Exceptions escaping the block. If the code under test raises, the exception propagates and the log assertion is skipped. Wrap the call in
assertRaisesinside theassertLogsblock when you expect both. - Over-specific tests. Asserting the full output list couples the test to every message. Prefer asserting that a specific record exists.
Putting it together
- Use
assertLogswith a parent logger name and an explicitlevel. - Check
levelno,args, orexc_infooncm.recordswhen wording may change. - Use
assertNoLogsfor paths that must stay silent. - Keep tests focused on events that operators depend on.
Exercise
A test uses with self.assertLogs("myapp", level="WARNING") as cm: and the code under test calls logging.getLogger("myapp.db").info("connected") and nothing else. What happens, and how do you fix the test if you want to check that message?
Show answer
The test fails with an AssertionError, because the INFO record is below the WARNING level and no record at WARNING or above was captured. To check the message, change the level to "INFO" (or "DEBUG"). The child logger myapp.db is captured through the parent name myapp, so the logger name can stay as it is. The expected output is ["INFO:myapp.db:connected"].
Exercise
Write a test for a function retry(op) that logs logger.warning("Attempt %d failed", n) on each failed attempt using logger myapp.retry. After two failed attempts the function succeeds. Assert that exactly two warnings were logged and that their args are (1,) and (2,).
Show answer
with self.assertLogs("myapp", level="WARNING") as cm: retry(op) self.assertEqual(len(cm.records), 2) self.assertEqual([r.args for r in cm.records], [(1,), (2,)])