Skip to content

Commit

Permalink
Improve "InterceptHandler" recipe for frozen modules
Browse files Browse the repository at this point in the history
  • Loading branch information
Delgan committed Dec 31, 2024
1 parent dfe9607 commit 34a4a71
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 7 deletions.
12 changes: 8 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
11 changes: 8 additions & 3 deletions tests/test_interception.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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:
Expand Down Expand Up @@ -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"

0 comments on commit 34a4a71

Please sign in to comment.