ecs-logging-python icon indicating copy to clipboard operation
ecs-logging-python copied to clipboard

StructlogProcessor fails typechecking

Open AWhetter opened this issue 1 year ago • 2 comments

When typechecking the following code:

from structlog.typing import Processor

shared_processors: tuple[Processor, ...] = (
    structlog.contextvars.merge_contextvars,
    structlog.processors.add_log_level,
    structlog.processors.StackInfoRenderer(),
    structlog.dev.set_exc_info,
    structlog.processors.TimeStamper(fmt="iso", utc=True),
)

processors: list[Processor]
if sys.stderr.isatty():
    processors = [
        *shared_processors,
        structlog.dev.ConsoleRenderer(),
    ]
else:
    processors = [
        *shared_processors,
        structlog.processors.dict_tracebacks,
        ecs_logging.StructlogFormatter(),
    ]

structlog.configure(
    processors=processors,
    logger_factory=structlog.PrintLoggerFactory(),
    cache_logger_on_first_use=True,
)

mypy raises the following:

error: List item 2 has incompatible type "StructlogFormatter"; expected
"Callable[[Any, str, MutableMapping[str, Any]], Union[Mapping[str, Any], str, bytes, bytearray, tuple[Any, ...]]]"  [list-item]
            ecs_logging.StructlogFormatter(),
            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
note: "StructlogFormatter.__call__" has type "Callable[[Arg(Any, '_'), Arg(str, 'name'), Arg(dict[str, Any], 'event_dict')], str]"

StructlogFormatter is annotated as accepting a dict[str, Any], but it needs to accept any MutableMapping[str, Any]. The code already conforms to this, so addressing this issue wil hopefully only involve updating the type annotation.

AWhetter avatar Oct 23 '24 23:10 AWhetter

@AWhetter thanks for reporting. We should probably run mypy in CI too to avoid regressions. Any chance you can provide a pull request?

xrmx avatar Oct 24 '24 07:10 xrmx

I've made a pull request, and I'm in the process of getting the CLA signed by my employer. Hopefully I'm running mypy in the way that you were intending. mypy is already run by the github actions, but I'm running this as part of the tests. It's probably not necessary to be testing that mypy operates correctly in all versions of Python, but it is and it works.

AWhetter avatar Oct 24 '24 18:10 AWhetter