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
