【FastAPI 学习 四】 日志配置

FastAPI 中日志的配置

本系列博客是配合Vue开发一套后台管理系统,对应的Vue教程见个人博客
https://www.charmcode.cn/

在Python中内置了logging模块, 但是配置有丢丢麻烦。

于是有人开发了这样的一个日志扩展库loguru

我很喜欢它 Github地址 https://github.com/Delgan/loguru

loguru 使用

自己看官网
http://loguru.readthedocs.io/

或者GitHub README.md的演示,基本就够了

集成到FastAPI

本来是想 像flask那样把日志对象挂载到app对象上,作者建议直接使用全局对象

issues https://github.com/tiangolo/fastapi/issues/81#issuecomment-473677039

所以了,我是在项目中,直接新建了一个文件夹extensions/专门存放扩展文件
然后在文件目录下创建了extensions/logger.py文件, 简单配置

import os
import time
from loguru import logger

basedir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# print(f"log basedir{basedir}")  # /xxx/python_code/FastAdmin/backend/app
# 定位到log日志文件
log_path = os.path.join(basedir, 'logs')

if not os.path.exists(log_path):
    os.mkdir(log_path)

log_path_error = os.path.join(log_path, f'{time.strftime("%Y-%m-%d")}_error.log')

# 日志简单配置
# 具体其他配置 可自行参考 https://github.com/Delgan/loguru
logger.add(log_path_error, rotation="12:00", retention="5 days", enqueue=True)

使用

使用也是特别方便的

# 得先在 extensions/__init__.py导入logger 才可以这样导入logger
from extensions import logger
logger.debug(f"日志记录")
logger.info(f"日志记录")
logger.error(f"xxx")

日志小技巧

使用官方内置的库traceback能帮你更加详细的打印错误栈。

import traceback

logger.error(traceback.format_exc())

Sentry

项目复杂后,可以考虑用这个Sentry日志处理系统。

https://docs.sentry.io/platforms/python/guides/asgi/
https://www.starlette.io/middleware/
可参考 starlette middleware 使用

对应GitHub地址

https://github.com/CoderCharm/fastapi-mysql-generator

见个人博客 https://www.charmcode.cn/article/2020-07-12_FastAPI_logger

posted @ 2020-12-25 23:03  王小右  阅读(3241)  评论(0编辑  收藏  举报