-
-
Notifications
You must be signed in to change notification settings - Fork 198
🦄 refactor: optimize log output #345
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,53 +2,120 @@ | |
# -*- coding: utf-8 -*- | ||
from __future__ import annotations | ||
|
||
import inspect | ||
import logging | ||
import os | ||
|
||
from typing import TYPE_CHECKING | ||
|
||
from loguru import logger | ||
|
||
from backend.core import path_conf | ||
from backend.core.conf import settings | ||
|
||
if TYPE_CHECKING: | ||
import loguru | ||
|
||
|
||
class Logger: | ||
def __init__(self): | ||
self.log_path = path_conf.LOG_DIR | ||
|
||
def log(self) -> loguru.Logger: | ||
if not os.path.exists(self.log_path): | ||
os.mkdir(self.log_path) | ||
|
||
# 日志文件 | ||
log_stdout_file = os.path.join(self.log_path, settings.LOG_STDOUT_FILENAME) | ||
log_stderr_file = os.path.join(self.log_path, settings.LOG_STDERR_FILENAME) | ||
|
||
# loguru 日志: https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.add | ||
log_config = dict(rotation='10 MB', retention='15 days', compression='tar.gz', enqueue=True) | ||
# stdout | ||
logger.add( | ||
log_stdout_file, | ||
level='INFO', | ||
filter=lambda record: record['level'].name == 'INFO' or record['level'].no <= 25, | ||
**log_config, | ||
backtrace=False, | ||
diagnose=False, | ||
) | ||
# stderr | ||
logger.add( | ||
log_stderr_file, | ||
level='ERROR', | ||
filter=lambda record: record['level'].name == 'ERROR' or record['level'].no >= 30, | ||
**log_config, | ||
backtrace=True, | ||
diagnose=True, | ||
) | ||
|
||
return logger | ||
|
||
|
||
log = Logger().log() | ||
|
||
class InterceptHandler(logging.Handler): | ||
""" | ||
Default handler from examples in loguru documentaion. | ||
See https://loguru.readthedocs.io/en/stable/overview.html#entirely-compatible-with-standard-logging | ||
""" | ||
|
||
def emit(self, record: logging.LogRecord): | ||
# 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 | ||
# print(frame, depth) | ||
# while frame and frame.f_code and frame.f_code.co_filename == logging.__file__: | ||
# frame = frame.f_back | ||
# depth += 1 | ||
|
||
# Find caller from where originated the logged message. | ||
# 换成inspect获取 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Delete this comment. |
||
frame, depth = inspect.currentframe(), 0 | ||
while frame and (depth == 0 or 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()) | ||
|
||
|
||
def setup_logging(log_level: str = 'INFO'): | ||
""" | ||
from https://pawamoy.github.io/posts/unify-logging-for-a-gunicorn-uvicorn-app/ | ||
https://github.com/pawamoy/pawamoy.github.io/issues/17 | ||
""" | ||
|
||
from sys import stderr, stdout | ||
|
||
logger.configure(handlers=[{'sink': stdout, 'serialize': 0, 'level': log_level}]) | ||
logger.configure(handlers=[{'sink': stderr, 'serialize': 0, 'level': log_level}]) | ||
|
||
# intercept everything at the root logger | ||
logging.root.handlers = [InterceptHandler()] | ||
logging.root.setLevel(log_level) | ||
|
||
# remove every other logger's handlers | ||
# and propagate to root logger | ||
# noinspection PyUnresolvedReferences | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The comment here does not match the code |
||
|
||
# https://segmentfault.com/a/1190000042197982 | ||
# uvicorn的两种方式启动,命令行正常,代码方式启动uvicorn.access可能会缺失 | ||
# 如果缺失则添加 | ||
# if "uvicorn.error" in logging.root.manager.loggerDict.keys() and "uvicorn.access" not in logging.root.manager.loggerDict.keys(): | ||
# uvicorn_access_logger = logging.getLogger("uvicorn.access") | ||
# uvicorn_access_logger.handlers = [] | ||
|
||
for name in logging.root.manager.loggerDict.keys(): | ||
# if 'uvicorn' in name : | ||
logging.getLogger(name).handlers = [] | ||
# propagate是可选项,其默认是为1,表示消息将会传递给高层次logger的handler,通常我们需要指定其值为0 | ||
# 设置1,传给loguru | ||
|
||
# logging.info(f"{logging.getLogger(name)}, {logging.getLogger(name).propagate}") | ||
if 'uvicorn.access' in name or 'watchfiles.main' in name: | ||
logging.getLogger(name).propagate = False | ||
else: | ||
logging.getLogger(name).propagate = True | ||
|
||
logging.debug(f'{logging.getLogger(name)}, {logging.getLogger(name).propagate}') | ||
|
||
logger.remove() | ||
logger.configure(handlers=[{'sink': stdout, 'serialize': 0, 'level': log_level}]) | ||
logger.configure(handlers=[{'sink': stderr, 'serialize': 0, 'level': log_level}]) | ||
|
||
|
||
def set_customize_logfile(): | ||
log_path = path_conf.LOG_DIR | ||
if not os.path.exists(log_path): | ||
os.mkdir(log_path) | ||
|
||
# 日志文件 | ||
log_stdout_file = os.path.join(log_path, settings.LOG_STDOUT_FILENAME) | ||
log_stderr_file = os.path.join(log_path, settings.LOG_STDERR_FILENAME) | ||
|
||
# loguru 日志: https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.add | ||
log_config = dict(rotation='10 MB', retention='15 days', compression='tar.gz', enqueue=True) | ||
# stdout | ||
logger.add( | ||
log_stdout_file, | ||
level='INFO', | ||
filter=lambda record: record['level'].name == 'INFO' or record['level'].no <= 25, | ||
**log_config, | ||
backtrace=False, | ||
diagnose=False, | ||
) | ||
# stderr | ||
logger.add( | ||
log_stderr_file, | ||
level='ERROR', | ||
filter=lambda record: record['level'].name == 'ERROR' or record['level'].no >= 30, | ||
**log_config, | ||
backtrace=True, | ||
diagnose=True, | ||
) | ||
|
||
|
||
log = logger |
This file contains hidden or 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
This file contains hidden or 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 suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Please delete the comments and code here.