Skip to content

Commit 2bbbbe7

Browse files
authored
Update the log output default style (#714)
* Update the log output default style * Update the log file compression * fix line * Add log summary
1 parent ef5e921 commit 2bbbbe7

File tree

5 files changed

+32
-20
lines changed

5 files changed

+32
-20
lines changed

backend/common/log.py

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,9 @@
88
from asgi_correlation_id import correlation_id
99
from loguru import logger
1010

11-
from backend.core import path_conf
1211
from backend.core.conf import settings
12+
from backend.core.path_conf import LOG_DIR
13+
from backend.utils.timezone import timezone
1314

1415

1516
class InterceptHandler(logging.Handler):
@@ -58,11 +59,11 @@ def setup_logging() -> None:
5859
# Debug log handlers
5960
# logging.debug(f'{logging.getLogger(name)}, {logging.getLogger(name).propagate}')
6061

61-
# 定义 correlation_id 默认过滤函数
62+
# correlation_id 过滤器
6263
# https://github.com/snok/asgi-correlation-id/issues/7
6364
def correlation_id_filter(record):
64-
cid = correlation_id.get(settings.LOG_CID_DEFAULT_VALUE)
65-
record['correlation_id'] = cid[: settings.LOG_CID_UUID_LENGTH]
65+
cid = correlation_id.get(settings.TRACE_ID_LOG_DEFAULT_VALUE)
66+
record['correlation_id'] = cid[: settings.TRACE_ID_LOG_UUID_LENGTH]
6667
return record
6768

6869
# 配置 loguru 处理器
@@ -81,13 +82,20 @@ def correlation_id_filter(record):
8182

8283
def set_custom_logfile() -> None:
8384
"""设置自定义日志文件"""
84-
log_path = path_conf.LOG_DIR
85-
if not os.path.exists(log_path):
86-
os.mkdir(log_path)
85+
if not os.path.exists(LOG_DIR):
86+
os.mkdir(LOG_DIR)
8787

8888
# 日志文件
89-
log_access_file = os.path.join(log_path, settings.LOG_ACCESS_FILENAME)
90-
log_error_file = os.path.join(log_path, settings.LOG_ERROR_FILENAME)
89+
log_access_file = os.path.join(LOG_DIR, settings.LOG_ACCESS_FILENAME)
90+
log_error_file = os.path.join(LOG_DIR, settings.LOG_ERROR_FILENAME)
91+
92+
# 日志压缩回调
93+
def compression(filepath):
94+
filename = filepath.split(os.sep)[-1]
95+
original_filename = filename.split('.')[0]
96+
if '-' in original_filename:
97+
return os.path.join(LOG_DIR, f'{original_filename}.log')
98+
return os.path.join(LOG_DIR, f'{original_filename}_{timezone.now().strftime("%Y-%m-%d")}.log')
9199

92100
# 日志文件通用配置
93101
# https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.add
@@ -96,7 +104,7 @@ def set_custom_logfile() -> None:
96104
'enqueue': True,
97105
'rotation': '00:00',
98106
'retention': '7 days',
99-
'compression': 'tar.gz',
107+
'compression': lambda filepath: os.rename(filepath, compression(filepath)),
100108
}
101109

102110
# 标准输出文件

backend/core/conf.py

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

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

149-
# 日志
150-
LOG_CID_DEFAULT_VALUE: str = '-'
151-
LOG_CID_UUID_LENGTH: int = 32 # 日志 correlation_id 长度,必须小于等于 32
151+
# 日志(控制台)
152152
LOG_STD_LEVEL: str = 'INFO'
153153
LOG_STD_FORMAT: str = (
154154
'<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</> | <lvl>{level: <8}</> | <cyan>{correlation_id}</> | <lvl>{message}</>'
155155
)
156+
# 日志(文件)
156157
LOG_ACCESS_FILE_LEVEL: str = 'INFO'
157158
LOG_ERROR_FILE_LEVEL: str = 'ERROR'
158159
LOG_ACCESS_FILENAME: str = 'fba_access.log'

backend/middleware/access_middleware.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,7 @@ async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -
2323
path = request.url.path if not request.url.query else request.url.path + '/' + request.url.query
2424

2525
if request.method != 'OPTIONS':
26-
log.info(f'--> 请求开始[{path}]')
27-
log.info(f'请求方式:[{request.method}]')
26+
log.debug(f'--> 请求开始[{path}]')
2827

2928
perf_time = time.perf_counter()
3029
request.state.perf_time = perf_time
@@ -37,8 +36,11 @@ async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -
3736
elapsed = (time.perf_counter() - perf_time) * 1000
3837

3938
if request.method != 'OPTIONS':
40-
log.info(f'接口耗时:[{elapsed:.3f}]ms')
41-
log.info(f'接口状态:[{response.status_code}]')
42-
log.info('<-- 请求结束')
39+
log.debug('<-- 请求结束')
40+
41+
log.info(
42+
f'{request.client.host: <15} | {request.method: <8} | {response.status_code: <6} | '
43+
f'{path} | {elapsed:.3f}ms'
44+
)
4345

4446
return response

backend/middleware/opera_log_middleware.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ async def dispatch(self, request: Request, call_next: Any) -> Response:
8282
username = None
8383

8484
# 日志记录
85+
log.debug(f'接口摘要:[{summary}]')
8586
log.debug(f'请求地址:[{request.state.ip}]')
8687
log.debug(f'请求参数:{args}')
8788

backend/utils/trace_id.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,4 @@ def get_request_trace_id(request: Request) -> str:
1212
:param request: FastAPI 请求对象
1313
:return:
1414
"""
15-
return request.headers.get(settings.TRACE_ID_REQUEST_HEADER_KEY) or settings.LOG_CID_DEFAULT_VALUE
15+
return request.headers.get(settings.TRACE_ID_REQUEST_HEADER_KEY) or settings.TRACE_ID_LOG_DEFAULT_VALUE

0 commit comments

Comments
 (0)