1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
| import logging import logging.config import json import sys from datetime import datetime from typing import Dict, Any import os
class JSONFormatter(logging.Formatter): """JSON格式化器""" def format(self, record: logging.LogRecord) -> str: log_data = { "timestamp": datetime.utcnow().isoformat(), "level": record.levelname, "logger": record.name, "message": record.getMessage(), "module": record.module, "function": record.funcName, "line": record.lineno } if record.exc_info: log_data["exception"] = self.formatException(record.exc_info) if hasattr(record, 'extra_fields'): log_data.update(record.extra_fields) for key, value in record.__dict__.items(): if key not in ['name', 'msg', 'args', 'levelname', 'levelno', 'pathname', 'filename', 'module', 'lineno', 'funcName', 'created', 'msecs', 'relativeCreated', 'thread', 'threadName', 'processName', 'process', 'getMessage', 'exc_info', 'exc_text', 'stack_info']: log_data[key] = value return json.dumps(log_data, ensure_ascii=False, default=str)
class ContextFilter(logging.Filter): """上下文过滤器,添加请求上下文信息""" def filter(self, record: logging.LogRecord) -> bool: try: from contextvars import copy_context context = copy_context() request_id = context.get('request_id', None) if request_id: record.request_id = request_id user_id = context.get('user_id', None) if user_id: record.user_id = user_id except: pass return True
LOGGING_CONFIG = { "version": 1, "disable_existing_loggers": False, "formatters": { "json": { "()": JSONFormatter, }, "standard": { "format": "%(asctime)s [%(levelname)s] %(name)s: %(message)s" } }, "filters": { "context_filter": { "()": ContextFilter, } }, "handlers": { "console": { "level": "INFO", "class": "logging.StreamHandler", "formatter": "json" if os.getenv("LOG_FORMAT") == "json" else "standard", "filters": ["context_filter"], "stream": sys.stdout }, "file": { "level": "DEBUG", "class": "logging.handlers.RotatingFileHandler", "formatter": "json", "filters": ["context_filter"], "filename": "logs/app.log", "maxBytes": 10485760, "backupCount": 5 }, "error_file": { "level": "ERROR", "class": "logging.handlers.RotatingFileHandler", "formatter": "json", "filters": ["context_filter"], "filename": "logs/error.log", "maxBytes": 10485760, "backupCount": 10 } }, "loggers": { "": { "handlers": ["console", "file", "error_file"], "level": "INFO", "propagate": False }, "uvicorn": { "handlers": ["console"], "level": "INFO", "propagate": False }, "sqlalchemy.engine": { "handlers": ["file"], "level": "WARNING", "propagate": False } } }
logging.config.dictConfig(LOGGING_CONFIG)
os.makedirs("logs", exist_ok=True)
|