Last active
January 11, 2022 13:41
-
-
Save Dysta/a88909902e4105f4ddcd9a94e4c4cbe0 to your computer and use it in GitHub Desktop.
Redirect nextcord log to loguru
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
class InterceptHandler(logging.Handler): | |
""" | |
This class is used to Intercept logging message and | |
log those into loguru | |
""" | |
def emit(self, record) -> None: | |
""" | |
Overriding of emit method from logging.Handler | |
Code from: https://loguru.readthedocs.io/en/stable/overview.html?highlight=emit#entirely-compatible-with-standard-logging | |
:param record: the record to log | |
:return: None | |
""" | |
# 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, lazy=True).log( | |
level, record.getMessage() | |
) | |
# those line are here to recreate a similare output to https://nextcord.readthedocs.io/en/latest/logging.html | |
fmt = "{time:YYYY-MM-DD at HH:mm:ss}:{level}:{name}: {message}" | |
logger.add( | |
f"./logs/log-{datetime.datetime.now():%Y-%m-%d}.log", | |
level="DEBUG", | |
format=fmt, | |
filter=lambda record: record.get("level").no != 10, # we are not logging DEBUG information | |
rotation="01:00", | |
retention="10 days", | |
enqueue=True, | |
mode="w", | |
encoding="utf-8", | |
) | |
logging.basicConfig(handlers=[InterceptHandler()], level=0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment