日志纪录器

本文介绍了如何在FastAPI项目中设置和配置logging,包括使用logging_config.py定义日志格式和handler,以及如何在路由处理函数中添加日志记录。还提及了在大型项目中处理日志文件旋转和清理的重要性,以及Pythonlogging.handlers模块提供的相关工具。
摘要由CSDN通过智能技术生成

logging_config.py

import logging
import logging.config

LOGGING = {
‘version’: 1,
‘disable_existing_loggers’: False,
‘formatters’: {
‘verbose’: {
‘format’: ‘%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s’
},
‘simple’: {
‘format’: ‘%(levelname)s %(message)s’
},
},
‘handlers’: {
‘console’: {
‘level’: ‘DEBUG’,
‘class’: ‘logging.StreamHandler’,
‘formatter’: ‘verbose’,
},
‘file’: {
‘level’: ‘DEBUG’,
‘class’: ‘logging.FileHandler’,
‘filename’: ‘app.log’,
‘formatter’: ‘verbose’,
},
},
‘loggers’: {
‘fastapi’: {
‘handlers’: [‘console’, ‘file’],
‘level’: ‘DEBUG’,
‘propagate’: True,
},
},
}

def setup_logging():
logging.config.dictConfig(LOGGING)

main.py

from fastapi import FastAPI
from logging_config import setup_logging

app = FastAPI()

配置日志

setup_logging()

… 其他的FastAPI应用代码 …

某个路由处理函数或模块

import logging

logger = logging.getLogger(‘fastapi’)

@app.get(“/items/{item_id}”)
async def read_item(item_id: str):
logger.info(f"Reading item {item_id}")
# … 其他代码 …
return {“item_id”: item_id}

  1. 日志旋转和清理
    对于大型项目,你可能还需要考虑日志文件的旋转和清理策略,以避免日志文件过大或占用过多磁盘空间。Python的logging.handlers模块提供了RotatingFileHandler和TimedRotatingFileHandler等类,可以帮助你实现这些功能。
  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值