pytest-structlog

1.2 · active · verified Thu Apr 16

pytest-structlog is a pytest plugin that provides structured logging assertions for structlog. It integrates a 'log' fixture into your tests, allowing you to capture and make assertions against structlog events. The library is currently at version 1.2 and maintains a fairly active release cadence, with new versions typically released monthly or quarterly.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use the `log` fixture provided by pytest-structlog. It shows how to capture structlog events from a function under test and then assert their presence and content using `log.events`, `log.has()`, and `log.count()`.

import structlog
from pytest_structlog import StructuredLogCapture

# your_lib.py (or code under test)
logger = structlog.get_logger()

def do_something():
    logger.info("Starting process", task_id="abc-123")
    for i in range(2):
        logger.debug("Step complete", step=i)
    logger.warning("Process finished with warnings", result="partial", count=2)

# test_your_lib.py
def test_do_something(log: StructuredLogCapture):
    assert len(log.events) == 0 # No logs captured initially

    do_something()

    # Assert on specific event counts
    assert log.count("Starting process", level="info") == 1
    assert log.count("Step complete", level="debug") == 2

    # Assert on individual events with context
    assert log.has("Starting process", task_id="abc-123")
    assert log.has("Step complete", step=0)
    assert log.has("Step complete", step=1)
    assert log.has("Process finished with warnings", result="partial", count=2, level="warning")

    # You can also inspect all captured events directly
    expected_events = [
        log.info("Starting process", task_id="abc-123"),
        log.debug("Step complete", step=0),
        log.debug("Step complete", step=1),
        log.warning("Process finished with warnings", result="partial", count=2)
    ]
    assert log.events == expected_events

view raw JSON →