使用中间件全局捕获异常,再进行注册使用
from fastapi import FastAPI, Request
from pathlib import Path
from loguru import logger
def create_app():
api = FastAPI(title=settings.TITLE, description=settings.DESC, version='1.0.0', docs_url='/docs')
# 跨域
register_cors(api)
# redis
register_redis(api)
# 路由
register_router(api)
# 后台
register_admin(api)
# 定时任务
# register_aps(api, settings.SQLALCHEMY_DATABASE_URL2)
# 日志
register_log(api)
return api
def register_log(api: FastAPI):
@api.middleware('http')
async def add_log(request: Request, call_next):
url = request.url
log_dir = BACKEND_DIR / 'logs'
log_path = log_dir / f'{time.strftime("%Y-%m-%d")}.log'
# 不在终端打印
logger.remove(handler_id=None)
# diagnose backtrace 为true 日志内将增加回溯, format也可以格式化处理
# message