Skip to content

Clarification on InterceptHandler behavior #1404

@BayerSe

Description

@BayerSe

Hello,

I've got another question where I'd need some help. In particular, I'd like to understand the following behavior. If I open a fresh console and print all loggers

import logging
for logger in [logging.getLogger(name) for name in logging.root.manager.loggerDict]:
    print(logger)

I get the following output:

<Logger _plotly_utils.optional_imports (WARNING)>
<Logger _plotly_utils (WARNING)>
<Logger _shaded_thriftpy.server (DEBUG)>
<Logger _shaded_thriftpy (DEBUG)>
<Logger concurrent.futures (WARNING)>
<Logger concurrent (WARNING)>
<Logger asyncio (WARNING)>

... a mixture of different loggers and log levels.

If I now apply the InterceptHandler and reprint the loggers:

import inspect
import logging

from loguru import logger


class InterceptHandler(logging.Handler):
    def emit(self, record: logging.LogRecord) -> None:
        # Get corresponding Loguru level if it exists.
        level: str | int
        try:
            level = logger.level(record.levelname).name
        except ValueError:
            level = record.levelno

        # Find caller from where originated the logged message.
        frame, depth = inspect.currentframe(), 0
        while frame and (depth == 0 or frame.f_code.co_filename == logging.__file__):
            frame = frame.f_back
            depth += 1

        logger.opt(depth=depth, exception=record.exc_info).log(
            level, record.getMessage()
        )


logging.basicConfig(handlers=[InterceptHandler()], level=0, force=True)

for logger in [logging.getLogger(name) for name in logging.root.manager.loggerDict]:
    print(logger)

I get

<Logger _plotly_utils.optional_imports (NOTSET)>
<Logger _plotly_utils (NOTSET)>
<Logger _shaded_thriftpy.server (DEBUG)>
<Logger _shaded_thriftpy (DEBUG)>
<Logger concurrent.futures (NOTSET)>
<Logger concurrent (NOTSET)>
<Logger asyncio (NOTSET)>

I guess that the NOTSET comes from level=0 in the basicConfig call? If that is the case, why are _shaded_thriftpy.server and _shaded_thriftpy still at DEBUG?

This happens for other libraries too, not only the internal stuff: some stay at their original level, some switch to NOTSET.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions