日志配置
修改日志记录文件
- app/infrastructure/logger.py
注意
- 每个日志文件的大小不能超过 10MB。
- 日志文件保留 30 天。
- 日志文件按日期分卷,文件名格式为 info.log、info.1.log 等。
- 日志文件按级别分卷,文件名格式为 info.log、warning.log、error.log 等。
- 最多保留30天.超出后删除掉最开始的日志文件。
- 代码如下
python
import logging
import re
from datetime import date, timedelta
from pathlib import Path
from core.config import get_settings
LOG_DIR = Path(__file__).resolve().parents[3] / "logs"
MAX_LOG_BYTES = 10 * 1024 * 1024
LOG_RETENTION_DAYS = 30
_LOG_FILE_PATTERN = re.compile(r"(info|warning|error)(?:\.([1-9][0-9]*))?\.log")
_DATE_PATTERN = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}")
class _DailySizeRotatingHandler(logging.Handler):
"""按日期、级别和大小分卷;适用于单进程中的多线程日志写入。
文件示例:logs/2026-11-05/info.log、info.1.log。
多进程部署时应通过队列交给一个进程写入,不要共享这些日志文件。
"""
_manus_file_handler = True
def __init__(self, log_dir: Path, max_bytes: int = MAX_LOG_BYTES):
# UTF-8 单个字符最多占 4 字节,分卷不能截断字符。
if max_bytes < 4:
raise ValueError("max_bytes must be at least 4")
super().__init__(level=logging.INFO)
self.log_dir = Path(log_dir)
self.max_bytes = max_bytes
self._indices: dict[str, int] = {}
self._switch_day(date.today())
def _switch_day(self, today: date) -> None:
self.log_dir.mkdir(parents=True, exist_ok=True)
self._cleanup_expired_logs(today)
self._directory = self.log_dir / today.isoformat()
self._directory.mkdir(parents=True, exist_ok=True)
self._indices.clear()
self._day = today
def _cleanup_expired_logs(self, today: date) -> None:
# 含当天保留 30 个自然日,按日期从最早的目录开始清理。
cutoff = today - timedelta(days=LOG_RETENTION_DAYS - 1)
for directory in sorted(self.log_dir.iterdir()):
if (
directory.is_symlink()
or not directory.is_dir()
or not _DATE_PATTERN.fullmatch(directory.name)
):
continue
try:
log_date = date.fromisoformat(directory.name)
except ValueError:
continue
if log_date >= cutoff:
continue
for path in directory.iterdir():
if (
_LOG_FILE_PATTERN.fullmatch(path.name)
and not path.is_symlink()
and path.is_file()
):
path.unlink()
# 不递归删除,避免误删日期目录中的其他文件。
if not any(directory.iterdir()):
directory.rmdir()
def _current_path(self, level_name: str) -> Path:
if level_name not in self._indices:
indices = [0]
for path in self._directory.glob(f"{level_name}*.log"):
match = _LOG_FILE_PATTERN.fullmatch(path.name)
if match and path.is_file():
indices.append(int(match.group(2) or 0))
# 重启后接着最新分卷写入,不覆盖已有日志。
self._indices[level_name] = max(indices)
index = self._indices[level_name]
suffix = f".{index}" if index else ""
return self._directory / f"{level_name}{suffix}.log"
def _write(self, level_name: str, data: bytes) -> None:
offset = 0
view = memoryview(data)
while offset < len(data):
path = self._current_path(level_name)
size = path.stat().st_size if path.exists() else 0
# 普通日志完整写入一卷,超长日志从新卷开始拆分。
if size and size + len(data) - offset > self.max_bytes:
self._indices[level_name] += 1
continue
end = min(offset + self.max_bytes - size, len(data))
while end < len(data) and data[end] & 0xC0 == 0x80:
end -= 1
# 二进制写入避免 Windows 换行转换使实际大小超过上限。
with path.open("ab") as stream:
stream.write(view[offset:end])
offset = end
def emit(self, record: logging.LogRecord) -> None:
if record.levelno == logging.INFO:
level_name = "info"
elif record.levelno == logging.WARNING:
level_name = "warning"
elif record.levelno >= logging.ERROR:
level_name = "error"
else:
return
try:
today = date.today()
if today != self._day:
self._switch_day(today)
data = (self.format(record) + "\n").encode("utf-8", errors="backslashreplace")
self._write(level_name, data)
except Exception:
# 遵循 logging 的错误处理方式,避免日志异常中断业务。
self.handleError(record)
def setup_logging() -> None:
"""配置根日志:日期目录、级别隔离、10 MiB 分卷及 30 天保留。
应在应用启动时调用;沿用 settings.log_level,DEBUG 不写入文件。
清理发生在初始化和跨天后的首次文件日志写入时。
"""
settings = get_settings()
level_name = settings.log_level.strip().upper()
log_level = getattr(logging, level_name, None)
if not isinstance(log_level, int):
raise ValueError(f"Invalid log level: {settings.log_level!r}")
formatter = logging.Formatter(
"%(asctime)s - %(name)s - %(levelname)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
handler = _DailySizeRotatingHandler(LOG_DIR)
handler.setFormatter(formatter)
root_logger = logging.getLogger()
# 只替换本模块的处理器,保留框架或调用方配置的其他处理器。
for existing in root_logger.handlers[:]:
if getattr(existing, "_manus_file_handler", False):
root_logger.removeHandler(existing)
existing.close()
root_logger.setLevel(log_level)
root_logger.addHandler(handler)挂载到main.py
python
import logging
from fastapi import FastAPI
from app.infrastructure.logging.logging import setup_logging
from core.config import get_settings
# 1.加载配置信息
settings = get_settings()
# 2.初始化日志,业务模块无需重复调用
setup_logging()
logger = logging.getLogger(__name__)
# 3.创建应用
app = FastAPI()
logger.info("应用初始化完成")使用方式
使用标准库
python
import logging
logging.info("正常信息") # info.log
logging.warning("警告信息") # warning.log
logging.error("错误信息") # error.log更推荐各业务模块这样写,日志中会显示模块名,方便定位:
python
import logging
logger = logging.getLogger(__name__)
logger.info("用户 %s 登录成功", user_id)
logger.warning("库存不足")
logger.error("请求失败")捕获异常并记录日志
- 捕获异常时使用
logger.exception(),会将错误信息和完整异常堆栈写入error.log:
python
try:
result = 1 / 0
except ZeroDivisionError:
logger.exception("计算失败")特别注意
WARNING
其他模块 不用重复调用setup_logging() 。 确保配置的LOG_LEVEL=INFO ,才能同时记录 INFO、WARNING 和 ERROR。