Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
cfxegbert opened this issue Jul 19, 2024 · 2 comments
Open

Comments

@cfxegbert
Copy link

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
Copy link
Owner

hynek commented Jul 24, 2024

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

@cfxegbert
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants