From 34a4a71e175e4e9086a07d5a5e97fabf2cae62d6 Mon Sep 17 00:00:00 2001 From: Delgan Date: Tue, 31 Dec 2024 18:23:36 +0100 Subject: [PATCH] Improve "InterceptHandler" recipe for frozen modules --- README.md | 12 ++++++++---- tests/test_interception.py | 11 ++++++++--- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index aa1bbf78..13f72075 100644 --- a/README.md +++ b/README.md @@ -317,17 +317,21 @@ Want to intercept standard `logging` messages toward your Loguru sinks? ```python class InterceptHandler(logging.Handler): - def emit(self, record: logging.LogRecord) -> None: + def emit(self, record): # Get corresponding Loguru level if it exists. - level: str | int try: - level = logger.level(record.levelname).name + level: int | str = 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__): + while frame: + filename = frame.f_code.co_filename + is_logging = filename == logging.__file__ + is_frozen = "importlib" in filename and "_bootstrap" in filename + if depth > 0 and not (is_logging or is_frozen): + break frame = frame.f_back depth += 1 diff --git a/tests/test_interception.py b/tests/test_interception.py index 3435ff2d..c2328fac 100644 --- a/tests/test_interception.py +++ b/tests/test_interception.py @@ -16,7 +16,12 @@ def emit(self, record): # 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__): + while frame: + filename = frame.f_code.co_filename + is_logging = filename == logging.__file__ + is_frozen = "importlib" in filename and "_bootstrap" in filename + if depth > 0 and not (is_logging or is_frozen): + break frame = frame.f_back depth += 1 @@ -31,7 +36,7 @@ def test_formatting(writer): expected = ( "tests.test_interception - test_interception.py - test_formatting - DEBUG - " - "10 - 39 - test_interception - This is the message\n" + "10 - 44 - test_interception - This is the message\n" ) with make_logging_logger("tests", InterceptHandler()) as logging_logger: @@ -158,4 +163,4 @@ def test_using_logging_function(writer): logging.warning("ABC") result = writer.read() - assert result == "test_using_logging_function 158 test_interception test_interception.py ABC\n" + assert result == "test_using_logging_function 163 test_interception test_interception.py ABC\n"