1. 为什么需要自定义Uvicorn日志配置
当你用Uvicorn运行FastAPI应用时,默认的日志会直接打印到控制台。这在开发环境可能够用,但生产环境会遇到三个典型问题:
- 日志分散:访问日志和错误日志混在一起,排查问题时得像淘金一样筛选
- 文件管理:日志文件会无限增长,最终撑爆磁盘空间
- 格式单一:缺少时间戳、进程ID等关键信息,就像没有标签的档案柜
上周我就踩了个坑:线上服务突然报错,但因为没有记录请求时间,花了3小时才定位到是凌晨的定时任务触发了BUG。这就是为什么我们需要TimedRotatingFileHandler——它像智能档案管理员,能按时间自动分割日志文件。
2. 揭秘Uvicorn默认日志机制
2.1 默认配置解析
Uvicorn的默认日志配置藏在源码的config.py里,核心结构是这样的:
# uvicorn/config.py
LOGGING_CONFIG = {
"version": 1,
"formatters": {
"default": {
"()": "uvicorn.logging.DefaultFormatter",
"fmt": "%(levelprefix)s %(message)s"
},
"access": {
"()": "uvicorn.logging.AccessFormatter",
"fmt": '%(levelprefix)s %(client_addr)s - "%(request_line)s" %(status_code)s'
}
},
"handlers": {
"default": {
"formatter": "default",
"class": "logging.StreamHandler",
"stream": "ext://sys.stderr"
},
"access": {
"formatter": "access",
"class": "logging.StreamHandler",
"stream": "ext://sys.stdout"
}
},
"loggers": {
"uvicorn.error": {"level": "INFO"},
"uvicorn.access": {"handlers": ["access"], "level": "INFO", "propagate": False}
}
}
关键点解读:
- 双通道设计:错误日志走stderr(红色),访问日志走stdout(绿色)
- 极简格式:默认只显示基础信息,比如访问日志是
127.0.0.1 - "GET / HTTP/1.1" 200 - 无文件输出:所有日志都输出到终端,生产环境这是灾难
2.2 配置加载原理
当调用uvicorn.run()时,会发生这样的加载流程:
graph TD
A[uvicorn.run()] --> B[Config.load()]
B --> C{是否有log_config参数?}
C -->|无| D[使用默认配置]
C -->|有| E[合并用户配置]
E --> F[logging.config.dictConfig()]
我在源码里发现个有意思的设计:即使你只提供部分配置,Uvicorn会用dictConfig的disable_existing_loggers=False保留未配置的日志器,避免"配置了A却丢了B"的问题。
3. 实战TimedRotatingFileHandler配置
3.1 基础配置模板
这是我经过多次测试验证的配置模板,直接复制就能用:
LOGGING_CONFIG = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"verbose": {
"()": "uvicorn.logging.DefaultFormatter",
"fmt": "%(asctime)s [%(process)d] %(levelprefix)s %(message)s",
"datefmt": "%Y-%m-%d %H:%M:%S"
},
"access": {
"()": "uvicorn.logging.AccessFormatter",
"fmt": '%(asctime)s [%(process)d] %(levelprefix)s %(client_addr)s - "%(request_line)s" %(status_code)s'
}
},
"handlers": {
"error_file": {
"formatter": "verbose",
"class": "logging.handlers.TimedRotatingFileHandler",
"filename": "logs/error.log",
"when": "midnight",
"backupCount": 7
},
"access_file": {
"formatter": "access",
"class": "logging.handlers.TimedRotatingFileHandler",
"filename": "logs/access.log",
"when": "midnight",
"backupCount": 7
}
},
"loggers": {
"uvicorn.error": {
"handlers": ["error_file"],
"level": "INFO"
},
"uvicorn.access": {
"handlers": ["access_file"],
"level": "INFO",
"propagate": False
}
}
}
参数说明:
when="midnight":每天零点切割日志backupCount=7:保留最近7天的日志processd:记录进程ID,多进程部署时必备
3.2 多进程安全方案
直接使用TimedRotatingFileHandler在多进程环境会出问题——多个进程同时切割日志时可能丢失数据。解决方案有两种:
方案一:改用ConcurrentLogHandler
pip install concurrent-log-handler
配置修改部分:
"handlers": {
"error_file": {
"class": "concurrent_log_handler.ConcurrentRotatingFileHandler",
"filename": "logs/error.log",
"maxBytes": 100*1024*1024, # 100MB
"backupCount": 7
}
}
方案二:使用Linux的logrotate
# /etc/logrotate.d/your_app
/path/to/logs/*.log {
daily
rotate 7
compress
delaycompress
missingok
notifempty
create 644 root root
sharedscripts
postrotate
kill -USR1 $(cat /var/run/your_app.pid)
endscript
}
4. 高级配置技巧
4.1 动态日志路径
在Docker环境中,我推荐用环境变量动态设置路径:
import os
from pathlib import Path
LOG_DIR = os.getenv("LOG_DIR", "logs")
Path(LOG_DIR).mkdir(exist_ok=True)
LOGGING_CONFIG["handlers"]["error_file"]["filename"] = f"{LOG_DIR}/error.log"
4.2 结构化日志输出
配合JSON格式化器,方便接入ELK等系统:
"formatters": {
"json": {
"()": "pythonjsonlogger.jsonlogger.JsonFormatter",
"fmt": """
{
"time": "%(asctime)s",
"pid": "%(process)d",
"level": "%(levelname)s",
"message": "%(message)s"
}
"""
}
}
4.3 敏感信息过滤
在访问日志中隐藏密码等敏感信息:
class SafeAccessFormatter(uvicorn.logging.AccessFormatter):
def formatMessage(self, record):
msg = super().formatMessage(record)
if "/login?" in msg:
msg = re.sub(r'password=[^&]+', 'password=***', msg)
return msg
然后在配置中替换原有formatter:
"access": {
"()": "your_module.SafeAccessFormatter",
"fmt": "..."
}
5. 常见问题排查
Q1:日志文件没生成?
- 检查目录权限:
mkdir -p logs && chmod 777 logs - 确认配置路径是绝对路径
- 查看应用启动时是否报权限错误
Q2:日志切割时间不准?
- 时区问题:在Dockerfile中设置
ENV TZ=Asia/Shanghai - 服务器时间不同步:
ntpdate ntp.aliyun.com
Q3:日志内容缺失?
- 检查日志级别:DEBUG < INFO < WARNING < ERROR
- 确认propagate设置:True表示向上传递到父日志器
最近帮客户排查的一个典型案例:他们的K8s集群日志总是少最近5分钟的数据。最后发现是TimedRotatingFileHandler的缓存问题,解决方案是在handler配置中添加:
"handlers": {
"error_file": {
...,
"delay": False # 立即写入磁盘
}
}
1万+



被折叠的 条评论
为什么被折叠?



