Skip to content

Commit 863fe0d

Browse files
committed
Update log output config and format
1 parent fe3a3b4 commit 863fe0d

File tree

2 files changed

+34
-15
lines changed

2 files changed

+34
-15
lines changed

backend/common/log.py

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import inspect
44
import logging
55
import os
6+
import re
67
import sys
78

89
from asgi_correlation_id import correlation_id
@@ -36,6 +37,18 @@ def emit(self, record: logging.LogRecord):
3637
logger.opt(depth=depth, exception=record.exc_info).log(level, record.getMessage())
3738

3839

40+
def default_formatter(record):
41+
"""默认日志格式化程序"""
42+
43+
# 重写 sqlalchemy echo 输出
44+
# https://github.com/sqlalchemy/sqlalchemy/discussions/12791
45+
record_name = record['name'] or ''
46+
if record_name.startswith('sqlalchemy'):
47+
record['message'] = re.sub(r'\s+', ' ', record['message']).strip()
48+
49+
return settings.LOG_FORMAT if settings.LOG_FORMAT.endswith('\n') else f'{settings.LOG_FORMAT}\n'
50+
51+
3952
def setup_logging() -> None:
4053
"""
4154
设置日志处理器
@@ -48,9 +61,11 @@ def setup_logging() -> None:
4861
logging.root.handlers = [InterceptHandler()]
4962
logging.root.setLevel(settings.LOG_STD_LEVEL)
5063

51-
# 配置日志传播规则
5264
for name in logging.root.manager.loggerDict.keys():
65+
# 清空所有默认日志处理器
5366
logging.getLogger(name).handlers = []
67+
68+
# 配置日志传播规则
5469
if 'uvicorn.access' in name or 'watchfiles.main' in name:
5570
logging.getLogger(name).propagate = False
5671
else:
@@ -59,22 +74,24 @@ def setup_logging() -> None:
5974
# Debug log handlers
6075
# logging.debug(f'{logging.getLogger(name)}, {logging.getLogger(name).propagate}')
6176

77+
# 移除 loguru 默认处理器
78+
logger.remove()
79+
6280
# correlation_id 过滤器
6381
# https://github.com/snok/asgi-correlation-id/issues/7
6482
def correlation_id_filter(record):
6583
cid = correlation_id.get(settings.TRACE_ID_LOG_DEFAULT_VALUE)
66-
record['correlation_id'] = cid[: settings.TRACE_ID_LOG_UUID_LENGTH]
84+
record['correlation_id'] = cid[: settings.TRACE_ID_LOG_LENGTH]
6785
return record
6886

6987
# 配置 loguru 处理器
70-
logger.remove() # 移除默认处理器
7188
logger.configure(
7289
handlers=[
7390
{
7491
'sink': sys.stdout,
7592
'level': settings.LOG_STD_LEVEL,
93+
'format': default_formatter,
7694
'filter': lambda record: correlation_id_filter(record),
77-
'format': settings.LOG_STD_FORMAT,
7895
}
7996
]
8097
)
@@ -100,7 +117,7 @@ def compression(filepath):
100117
# 日志文件通用配置
101118
# https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.add
102119
log_config = {
103-
'format': settings.LOG_FILE_FORMAT,
120+
'format': default_formatter,
104121
'enqueue': True,
105122
'rotation': '00:00',
106123
'retention': '7 days',
@@ -110,7 +127,7 @@ def compression(filepath):
110127
# 标准输出文件
111128
logger.add(
112129
str(log_access_file),
113-
level=settings.LOG_ACCESS_FILE_LEVEL,
130+
level=settings.LOG_FILE_ACCESS_LEVEL,
114131
filter=lambda record: record['level'].no <= 25,
115132
backtrace=False,
116133
diagnose=False,
@@ -120,7 +137,7 @@ def compression(filepath):
120137
# 标准错误文件
121138
logger.add(
122139
str(log_error_file),
123-
level=settings.LOG_ERROR_FILE_LEVEL,
140+
level=settings.LOG_FILE_ERROR_LEVEL,
124141
filter=lambda record: record['level'].no >= 30,
125142
backtrace=True,
126143
diagnose=True,

backend/core/conf.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -143,22 +143,24 @@ class Settings(BaseSettings):
143143
IP_LOCATION_REDIS_PREFIX: str = 'fba:ip:location'
144144
IP_LOCATION_EXPIRE_SECONDS: int = 60 * 60 * 24 # 1 天
145145

146-
# 日志(Trace ID)
146+
# Trace ID
147147
TRACE_ID_REQUEST_HEADER_KEY: str = 'X-Request-ID'
148+
TRACE_ID_LOG_LENGTH: int = 32 # UUID 长度,必须小于等于 32
148149
TRACE_ID_LOG_DEFAULT_VALUE: str = '-'
149-
TRACE_ID_LOG_UUID_LENGTH: int = 32 # UUID 长度,必须小于等于 32
150150

151-
# 日志(控制台)
152-
LOG_STD_LEVEL: str = 'INFO'
153-
LOG_STD_FORMAT: str = (
151+
# 日志
152+
LOG_FORMAT: str = (
154153
'<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</> | <lvl>{level: <8}</> | <cyan>{correlation_id}</> | <lvl>{message}</>'
155154
)
155+
156+
# 日志(控制台)
157+
LOG_STD_LEVEL: str = 'INFO'
158+
156159
# 日志(文件)
157-
LOG_ACCESS_FILE_LEVEL: str = 'INFO'
158-
LOG_ERROR_FILE_LEVEL: str = 'ERROR'
160+
LOG_FILE_ACCESS_LEVEL: str = 'INFO'
161+
LOG_FILE_ERROR_LEVEL: str = 'ERROR'
159162
LOG_ACCESS_FILENAME: str = 'fba_access.log'
160163
LOG_ERROR_FILENAME: str = 'fba_error.log'
161-
LOG_FILE_FORMAT: str = '{time:YYYY-MM-DD HH:mm:ss.SSS} | <lvl>{level: <8}</> | {correlation_id} | <lvl>{message}</>'
162164

163165
# 操作日志
164166
OPERA_LOG_PATH_EXCLUDE: list[str] = [

0 commit comments

Comments
 (0)