How InterceptHandler redirects standard logging to Loguru
mainThe InterceptHandler is a custom handler that extends logging.Handler. Its purpose is to intercept log records generated by the standard Python logging module and redirect them into the Loguru system.
How it works:
- Level Mapping: It maps standard logging levels (like
INFOorWARNING) to the correspondingLogurulevels. If a mapping is not found, it falls back to the numeric level of the record. - Stack Inspection: It uses
inspect.currentframe()to traverse the call stack. It searches for the first frame that does not belong to theloggingmodule. This allowsLoguruto correctly identify the original source of the log message (the correct file and line number). - Emission: It uses
logger.opt()to log the message, preserving exception details and the calculated stack depth.
This class is typically used by calling logging.basicConfig(handlers=[InterceptHandler()]) to ensure all standard logs are captured by Loguru.