Delgan / loguru

Python logging made (stupidly) simple
MIT License
18.69k stars 682 forks source link

Publicly expose the code turning a dict filter to a filter function? #1123

Closed afeblot closed 1 month ago

afeblot commented 2 months ago

I used to have a handler with a dict filter:

filteredModules = {
    'docker': 'WARNING',
    'urllib3': 'WARNING',
    'azure': 'WARNING',
    'kafka': 'WARNING',
}

For some reason, I've had to turn this filter into a function to perform some pre-checks which would maybe drop some records, before dealing with the dict part.

But I found no way to easily transform my dict into a function I could call. That part of the code is embedded in your Logger.add() function.

I had to monkey patch the filter to get it done, which is brittle and ugly:

logger.configure(
    handlers=[
        {
            'filter': filteredModules,
            ...
        },
        {
            ...
        }
    ]
    ...
)

currentFilter = logger._core.handlers[1]._filter # pylint: disable=protected-access
def myNewFilter(record):
    if ...my added checks...:
        return False
    return currentFilter(record)
logger._core.handlers[1]._filter = myNewFilter # pylint: disable=protected-access

I would have been happy to do something like this instead:

moduleFilter = loguru.createFilterFunctionFromDict(filteredModules)

def myNewFilter(record):
    if ...my added checks...:
        return False
    return moduleFilter(record)

logger.configure(
    handlers=[
        {
            'filter': myNewFilter,
            ...
        },
        {
            ...
        }
    ]
    ...
)

Or would you currently see a cleaner way to achieve this?

Delgan commented 2 months ago

Hi @afeblot.

To be honest, I prefer not to expose such a function publicly. I think that for more advanced use cases like yours, it's advisable to implement a custom function that fits the needs exactly.

The "dict filter" isn't vert complicated and is implemented here: https://github.com/Delgan/loguru/blob/2ba868ce403b8f7fe0d387286ff43d20ec94fc37/loguru/_filters.py#L12-L24

You could import it instead of patching the handler filter, but I'd say it's best to just copy/paste what is required and re-use it in your own function with the pre-checks you need.

afeblot commented 2 months ago

Hi @Delgan, Thanks for your answer. I can indeed use this function, but I was hoping for a clean way to avoid re-coding this part which provides all the required safety nets around the use of a dictionary filter: https://github.com/Delgan/loguru/blob/2ba868ce403b8f7fe0d387286ff43d20ec94fc37/loguru/_logger.py#L879-L915

Delgan commented 1 month ago

Sorry @afeblot but I don't really plan to expose such function publicly.

afeblot commented 1 month ago

Ok, I understand. I'll manage it on my own. Thanks anyway.