Skip to content

Using structlog's default CapturingLogger in unit tests leads to errors #176

@jbvaningen

Description

@jbvaningen

Today I spent some time on adding structlog-sentry to our logging setup, a very nice addition which I'm really happy with!

However, I noticed a small issue in our unit tests. We make use of structlog.testing.CapturingLoggerFactory to verify various log functionalities. This factory does not play nice with SentryProcessor.

To reproduce, you can use the following unit test:

import pytest
import structlog
from structlog.testing import CapturingLoggerFactory
from structlog_sentry import SentryProcessor


@pytest.fixture(scope="function")
def capturing_logger_factory() -> CapturingLoggerFactory:
    processors = [
        structlog.stdlib.add_log_level,  # required for SentryProcessor()
        SentryProcessor(),
    ]
    factory = CapturingLoggerFactory()
    structlog.configure(
        processors=processors,
        context_class=dict,
        logger_factory=factory,
    )
    return factory


def test_example(capturing_logger_factory: CapturingLoggerFactory) -> None:
    logger = structlog.get_logger("example")

    # Expected behaviour is that the logger can now be used. However, it fails
    # due to the 'name' property of logger, created by CapturingLoggerFactory,
    # not being set.
    with pytest.raises(TypeError):
        logger.info("Some log message")

    # If we set the name explicitly, it does work as expected
    capturing_logger_factory.logger.name = "some_name"
    logger.info("Some log message")
    assert len(capturing_logger_factory.logger.calls) == 1

It is currently quite easy to work around, but it would be nice to fix this (and not too hard I expect).

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions