Skip to content

Commit

Permalink
even better logging
Browse files Browse the repository at this point in the history
  • Loading branch information
johanlundberg committed Oct 30, 2023
1 parent 02cc5a4 commit d4520b7
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 19 deletions.
24 changes: 5 additions & 19 deletions src/auth_server/log.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,20 @@
# -*- coding: utf-8 -*-
import logging
import logging.config
import sys
from typing import Optional

from loguru import logger

from auth_server.log_handler import InterceptHandler

__author__ = "lundberg"


LOGURU_FORMAT = "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | <level>{level: <8}</level> |\
<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>"


class InterceptHandler(logging.Handler):
@logger.catch(default=True, onerror=lambda _: sys.exit(1))
def emit(self, record):
# Get corresponding Loguru level if it exists
try:
level = logger.level(record.levelname).name
except ValueError:
level = record.levelno

# Find caller from where originated the logged message
frame, depth = logging.currentframe(), 2
while frame.f_code.co_filename == logging.__file__:
frame = frame.f_back
depth += 1

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


# set up default python logger to be intercepted by loguru
logging.getLogger().handlers = [InterceptHandler()]
logging.getLogger().level = 0 # DEBUG

Expand Down
26 changes: 26 additions & 0 deletions src/auth_server/log_handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# -*- coding: utf-8 -*-
import logging
import sys

from loguru import _logger, logger

__author__ = "lundberg"


class InterceptHandler(logging.Handler):
@logger.catch(default=True, onerror=lambda _: sys.exit(1))
def emit(self, record):
# Get corresponding Loguru level if it exists
try:
level = logger.level(record.levelname).name
except ValueError:
level = record.levelno

# Find caller from where originated the logged message
frame, depth = logging.currentframe(), 2
skip_frames_in = [logging.__file__, __file__, _logger.__file__]
while frame.f_code.co_filename in skip_frames_in:
frame = frame.f_back
depth += 1

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

0 comments on commit d4520b7

Please sign in to comment.