From a20d3393b50d924e94dca24bf73cfd964b383cb7 Mon Sep 17 00:00:00 2001 From: Delgan <4193924+Delgan@users.noreply.github.com> Date: Tue, 31 Dec 2024 18:37:42 +0100 Subject: [PATCH] Improve "InterceptHandler" recipe for frozen modules (#1266) --- README.md | 10 +++++++--- tests/test_interception.py | 11 ++++++++--- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index aa1bbf78..f1e1059c 100644 --- a/README.md +++ b/README.md @@ -319,15 +319,19 @@ Want to intercept standard `logging` messages toward your Loguru sinks? 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 + level: str | int = 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"