|
@@ -1,5 +1,7 @@
|
|
|
import logging
|
|
import logging
|
|
|
import sys
|
|
import sys
|
|
|
|
|
+import json
|
|
|
|
|
+from datetime import datetime, timezone
|
|
|
from typing import Optional
|
|
from typing import Optional
|
|
|
|
|
|
|
|
from app.core.config import settings
|
|
from app.core.config import settings
|
|
@@ -9,8 +11,28 @@ try:
|
|
|
except Exception: # pragma: no cover - 运行时兜底
|
|
except Exception: # pragma: no cover - 运行时兜底
|
|
|
fluent_handler = None
|
|
fluent_handler = None
|
|
|
|
|
|
|
|
-# 定义一个全局的日志格式
|
|
|
|
|
-LOG_FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
|
|
|
|
|
|
+class JsonLogFormatter(logging.Formatter):
|
|
|
|
|
+ """
|
|
|
|
|
+ 将日志格式化为 JSON(每行一条),便于 Fluentd/ELK 检索。
|
|
|
|
|
+ """
|
|
|
|
|
+
|
|
|
|
|
+ def format(self, record: logging.LogRecord) -> str:
|
|
|
|
|
+ log_obj = {
|
|
|
|
|
+ "timestamp": datetime.now(timezone.utc).isoformat(timespec="milliseconds"),
|
|
|
|
|
+ "level": record.levelname,
|
|
|
|
|
+ "logger": record.name,
|
|
|
|
|
+ "message": record.getMessage(),
|
|
|
|
|
+ "module": record.module,
|
|
|
|
|
+ "funcName": record.funcName,
|
|
|
|
|
+ "lineNo": record.lineno,
|
|
|
|
|
+ "app": settings.APP_NAME,
|
|
|
|
|
+ "env": settings.APP_ENV
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ if record.exc_info:
|
|
|
|
|
+ log_obj["exception"] = self.formatException(record.exc_info)
|
|
|
|
|
+
|
|
|
|
|
+ return json.dumps(log_obj, ensure_ascii=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
def _build_fluent_handler() -> Optional[logging.Handler]:
|
|
def _build_fluent_handler() -> Optional[logging.Handler]:
|
|
@@ -52,8 +74,8 @@ def setup_logging():
|
|
|
if root_logger.hasHandlers():
|
|
if root_logger.hasHandlers():
|
|
|
root_logger.handlers.clear()
|
|
root_logger.handlers.clear()
|
|
|
|
|
|
|
|
- # 创建一个通用的格式化器
|
|
|
|
|
- formatter = logging.Formatter(LOG_FORMAT)
|
|
|
|
|
|
|
+ # 创建 JSON 格式化器(用于控制台与本地文件)
|
|
|
|
|
+ formatter = JsonLogFormatter()
|
|
|
|
|
|
|
|
# 1. 创建控制台处理器 (StreamHandler)
|
|
# 1. 创建控制台处理器 (StreamHandler)
|
|
|
# - 将日志输出到标准输出(您的终端)
|
|
# - 将日志输出到标准输出(您的终端)
|