OSPython.049: Test Python Logs with assertLogs and caplog

Original detailed colored-pencil illustration of an Asian woman programmer validating Python log warnings and unit-test results in a data center; bottom-left exact neon-green BitcoinVersus.tech watermark

OSPython.049 answers a practical operations question: does an application log the correct event at the right severity, and stay quiet when there is no warning? Monitoring and incident response depend on reliable evidence. Automated tests can catch missing warnings before deployment. The lesson follows OSPython.048 on logging shutdown and OSPython.047 on logger propagation. It tests a fictional equipment record, not a live sensor.

JCharisTech, “How To Unit Test Logging In Python (Asserting Logs),” published November 6, 2022. Direct tutorial on testing logging records and output; iframe playback remains independently unverified.

Capture log records instead of console text

A Python logging call creates a LogRecord, while handlers and formatters determine the final destination and presentation. Python’s official assertLogs documentation specifies that assertLogs succeeds when at least one matching record reaches the selected logger at or above a requested level. Its records list contains actual record objects; output contains formatted text. Named loggers make tests less sensitive to unrelated software.

Create the three unittest cases

Save the complete Python program below as test_logging.py. The temperature function records a WARNING at 80°C or higher, or an INFO message below the threshold. One test checks the warning’s level and formatted message, another ensures no warning occurred during ordinary operation, and a third tests the informational message. No hardware is controlled or queried.

import logging
import unittest

logger = logging.getLogger("lab.telemetry")

def record_temperature(celsius):
    if celsius >= 80:
        logger.warning("device temperature high: %s C", celsius)
        return "hot"
    logger.info("device temperature nominal: %s C", celsius)
    return "ok"

class LoggingTests(unittest.TestCase):
    def test_warning_record_and_level(self):
        with self.assertLogs("lab.telemetry", level="WARNING") as captured:
            state = record_temperature(84)
        self.assertEqual(state, "hot")
        self.assertEqual(len(captured.records), 1)
        record = captured.records[0]
        self.assertEqual(record.levelname, "WARNING")
        self.assertEqual(record.getMessage(), "device temperature high: 84 C")

    def test_normal_path_is_quiet_at_warning(self):
        with self.assertNoLogs("lab.telemetry", level="WARNING"):
            self.assertEqual(record_temperature(42), "ok")

    def test_normal_info_message(self):
        with self.assertLogs("lab.telemetry", level="INFO") as captured:
            record_temperature(42)
        self.assertEqual(captured.output, [
            "INFO:lab.telemetry:device temperature nominal: 42 C"
        ])

if __name__ == "__main__":
    unittest.main()

record.getMessage() resolves delayed %s formatting, allowing a reliable comparison with the final event text. Checking record count also detects duplicate warnings. The topic connects to OSPython.047, where propagation can unexpectedly produce repeated output. Avoid asserting arbitrary timestamps or machine-specific paths unless those values are under test.

Corey Schafer, “Python Tutorial: Logging Advanced — Loggers, Handlers, and Formatters.” Background on record routing and formatting; Python documentation governs exact test assertions.

Understand what assertNoLogs guarantees

assertNoLogs("lab.telemetry", level="WARNING") fails if the specified logger or a captured child emits a WARNING, ERROR, or CRITICAL entry. It does not prohibit lower-severity INFO or DEBUG messages. Python introduced the method in version 3.10, as recorded in the official unittest reference. A successful quiet-path test cannot establish an absence of errors outside its capture scope.

Use pytest’s caplog fixture

For teams using pytest, the caplog fixture can inspect logging levels, names and messages without configuring file destinations. Save the following code as test_caplog.py beside the first file. The official pytest logging guide documents caplog.at_level(), records, and record_tuples.

import logging
from test_logging import record_temperature

def test_warning_with_caplog(caplog):
    with caplog.at_level(logging.WARNING, logger="lab.telemetry"):
        result = record_temperature(85)
    assert result == "hot"
    assert ("lab.telemetry", logging.WARNING,
            "device temperature high: 85 C") in caplog.record_tuples

The assertion checks a precise tuple of logger name, numeric WARNING level and message. A broad search for the substring “high” would be less robust. When application code reconfigures root handlers or disables propagation, pytest’s capture can miss records, so keep fixture setup isolated. OSPython.046 on structured formatting explains the role of stable fields.

Tech With Tim, “Please Learn How To Write Tests in Python… • Pytest Tutorial,” February 25, 2025. Introductory pytest fixtures and assertions, not independent execution of the lab.

Run both frameworks and inspect the results

With Python 3.10 or newer, execute python -m unittest -v test_logging.py. To use the optional second framework, install pytest into a disposable virtual environment and run python -m pytest -q test_caplog.py. The actual editorial test environment used Python 3.13.5 and pytest 9.0.2. All three unittest cases and the single pytest case passed. Other interpreter versions, platforms and logging integrations were not tested.

python -m unittest -v test_logging.py
python -m pytest -q test_caplog.py

# Actual local result:
# unittest: Ran 3 tests — OK
# pytest: 1 passed

Improve the checks safely

Change the temperature input from 84 to 79 in a throwaway branch and predict which test should fail. Restore the code after observing the failure. In production, never include passwords, tokens or unnecessary identifiers in logs. Pair logging validation with the redaction techniques in OSPython.041. Passing tests prove the program emitted expected events under controlled inputs; they do not prove a device is healthy.

Takeaway: assertLogs checks required events, assertNoLogs guards quiet paths, and caplog offers pytest-based inspection. Compare actual records rather than assumed console output, and keep examples independent of live operations.

Editor’s Note: Example code was executed locally with Python 3.13.5 and pytest 9.0.2, yielding four passing tests. Official Python and pytest references govern API and version behavior. Three YouTube video identities were checked against public listings, but browser playback and mobile display were not independently tested. The 1200 × 630 original colored-pencil cover is editorial artwork, not a screenshot of an operational system.

We volunteer daily to ensure the credibility of the information on this platform is Verifiably True. If you would like to support to help further secure the integrity of our research initiatives, please scan the QR code below

Original BitcoinVersus.Tech optional donation QR code for 5,000 satoshis
Original BitcoinVersus.Tech QR for an optional 5,000-satoshi contribution. Verify the recipient and amount before sending.

Optional Bitcoin contributions support research. Independently confirm recipient 3C9o19EH5HSiwEPyCTmEKzxhNCbo2X6TTb and 5,000 satoshis in a compatible wallet. Transfers are generally irreversible.

Educational material only. No production device was connected or modified. Passing logging tests are not an engineering safety certification or a substitute for security review, financial advice, or investment advice.

Leave a Reply