Skip to content

log

InterceptHandler

Bases: Handler

Handler for intercepting records and outputting to loguru.

Source code in app/core/log.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class InterceptHandler(logging.Handler):  # pragma: no cover
    """Handler for intercepting records and outputting to loguru."""

    def emit(self, record: logging.LogRecord) -> None:
        """
        Intercepts log messages.
        Intercepts log records sent to the handler, adds additional context to
        the records, and outputs the record to the default loguru logger.

        Args:
        ----
            record: The log record
        """
        level: int | str = ""
        try:
            level = logger.level(record.levelname).name
        except ValueError:
            level = str(record.levelno)

        frame, depth = logging.currentframe(), 2
        while frame.f_code.co_filename == logging.__file__:
            if frame.f_back:
                frame = frame.f_back
            depth += 1

        logger.opt(depth=depth, exception=record.exc_info).log(level, record.getMessage())

emit(record)

Intercepts log messages. Intercepts log records sent to the handler, adds additional context to the records, and outputs the record to the default loguru logger.


record: The log record
Source code in app/core/log.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
def emit(self, record: logging.LogRecord) -> None:
    """
    Intercepts log messages.
    Intercepts log records sent to the handler, adds additional context to
    the records, and outputs the record to the default loguru logger.

    Args:
    ----
        record: The log record
    """
    level: int | str = ""
    try:
        level = logger.level(record.levelname).name
    except ValueError:
        level = str(record.levelno)

    frame, depth = logging.currentframe(), 2
    while frame.f_code.co_filename == logging.__file__:
        if frame.f_back:
            frame = frame.f_back
        depth += 1

    logger.opt(depth=depth, exception=record.exc_info).log(level, record.getMessage())

Logger

Bases: Logger

Implements and overrides the gunicorn logging interface. This class inherits from the standard gunicorn logger and overrides it by replacing the handlers with InterceptHandler in order to route the gunicorn logs to loguru.

Source code in app/core/log.py
15
16
17
18
19
20
21
22
23
24
25
26
class Logger(glogging.Logger):  # pragma: no cover
    """
    Implements and overrides the gunicorn logging interface.
    This class inherits from the standard gunicorn logger and overrides it by
    replacing the handlers with `InterceptHandler` in order to route the
    gunicorn logs to loguru.
    """

    def __init__(self, cfg: Any) -> None:
        super().__init__(cfg)
        logging.getLogger("gunicorn.error").handlers = [InterceptHandler()]
        logging.getLogger("gunicorn.access").handlers = [InterceptHandler()]