Created
October 5, 2023 22:18
-
-
Save illuzian/49fd5b389785d60bc5b11a0d423d372b to your computer and use it in GitHub Desktop.
Using Loguru With Django (or anything else really)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
from loguru import logger as loguru_logger | |
import sys | |
# You can register this handler with Python's standard logging library. | |
class InterceptHandler(logging.Handler): | |
def __init__(self, *args, **kwargs): | |
super().__init__(*args, **kwargs) | |
log_level = 'DEBUG' | |
log_format = ("<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level}</level> | " | |
"<c>{module}</c>:<c>{function}</c>:<c>{line}</c> <level>{message}</level> " | |
"((<level>ELAPSED={elapsed};FILE='{file}';</level>)) |||") | |
self.loguru_logger = loguru_logger | |
self.loguru_logger.remove() | |
log_console_target = sys.stderr | |
self.loguru_logger.add( | |
log_console_target, level=log_level, colorize=True, | |
format=log_format) | |
def emit(self, record): | |
logger_opt = loguru_logger.opt(depth=6, exception=record.exc_info) | |
logger_opt.log(record.levelname, record.getMessage()) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Add this setting to your config | |
# In this example, from the Django root the structure is tools/logging.py | |
LOGGING = { | |
"version": 1, | |
"handlers": { | |
"default": { | |
"level": "DEBUG", | |
"class": "tools.logging.InterceptHandler", | |
}, | |
}, | |
"loggers": { | |
"django": { | |
"handlers": ["default"], | |
"propagate": True, | |
}, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment