hynek / structlog

Simple, powerful, and fast logging for Python.
https://www.structlog.org/
Other
3.48k stars 220 forks source link

Feature request: Evaluate a processor chain at a given set of log levels #633

Open cfxegbert opened 2 months ago

cfxegbert commented 2 months ago

I find myself only wanting certain fields included in my logging at a few select log levels. Something like:

class ProcessAtLogLevels:
    """Evaluate a chain of processors at a given set log levels.

    Args:
        levels: Log levels at which to evaluate processor chain.
        processors: A chain of *structlog* processors that is used to process entries at the given log levels.
    """

    def __init__(self, levels: int | Collection[int], *, processors: Sequence[Processor] = ()):
        self._levels = levels if isinstance(levels, Collection) else (levels,)
        self._processors = processors

    def __call__(self, logger: WrappedLogger, method_name: str, event_dict: EventDict) -> EventDict:
        if structlog.processors.NAME_TO_LEVEL[method_name] in self._levels:
            for processor in self._processors:
                event_dict = processor(logger, method_name, event_dict)
        return event_dict

I'll end up with something like this in my processor chain:

ProcessAtLogLevels(
    {logging.DEBUG, logging.CRITICAL},
    processors=(
        structlog.processors.CallsiteParameterAdder(
            (structlog.processors.CallsiteParameter.LINENO, structlog.processors.CallsiteParameter.PATHNAME)
        ),
    ),
)

This will only add line numbers and pathname at the DEBUG and CRITICAL log levels.

hynek commented 2 months ago

Looks like you've been able to implement this yourself, thanks to structlog's composability?

cfxegbert commented 2 months ago

Yes I did implement it. Because of work restrictions I can not create a pull request for the feature.