Skip to content

Commit

Permalink
Improve typing of PropagateHandler and InterceptHandler
Browse files Browse the repository at this point in the history
  • Loading branch information
Delgan committed Sep 3, 2023
1 parent 901dc33 commit 2c585a1
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 7 deletions.
9 changes: 5 additions & 4 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,7 @@ Need to propagate `Loguru` messages to standard `logging`?
::

class PropagateHandler(logging.Handler):
def emit(self, record):
def emit(self, record: logging.LogRecord) -> None:
logging.getLogger(record.name).handle(record)

logger.add(PropagateHandler(), format="{message}")
Expand All @@ -416,16 +416,17 @@ Want to intercept standard `logging` messages toward your `Loguru` sinks?
::

class InterceptHandler(logging.Handler):
def emit(self, record):
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 = sys._getframe(6), 6
while frame and frame.f_code.co_filename == logging.__file__:
frame, depth = inspect.currentframe(), 0
while frame and (depth == 0 or frame.f_code.co_filename == logging.__file__):
frame = frame.f_back
depth += 1

Expand Down
6 changes: 3 additions & 3 deletions tests/test_interception.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import inspect
import logging
import sys

from loguru import logger

Expand All @@ -15,8 +15,8 @@ def emit(self, record):
level = record.levelno

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

Expand Down

0 comments on commit 2c585a1

Please sign in to comment.