FastAPI 学习之路(六十)打造系统的日志输出
生活随笔
收集整理的這篇文章主要介紹了
FastAPI 学习之路(六十)打造系统的日志输出
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
我們要搭建日志系統(tǒng),我們使用loguru,挺不錯的一個開源的日志系統(tǒng)。可以使用
pip install loguru
我們在common創(chuàng)建log.py使用方式也很簡單
import os
import time
from loguru import logger
#日志的路徑
log_path = os.path.join(os.getcwd(), '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')
logger.add(log_path_error, rotation="12:00", retention="5 days", enqueue=True)
我們看下如何使用
#首先去導(dǎo)入
from common.logs import logger
# 新建用戶
@usersRouter.post("/users/", tags=["users"])
def create_user(user: UserCreate, db: Session = Depends(get_db)):
"""
- **email**: 用戶的郵箱
- **password**: 用戶密碼
"""
logger.info("創(chuàng)建用戶")
db_crest = get_user_emai(db, user.email)
user.password = get_password_hash(user.password)
if not db_crest:
logger.success("創(chuàng)建用戶成功")
user=db_create_user(db=db, user=user)
return reponse(code=0,data={'user':user.email},message="success")
logger.error("賬號:{}不能重復(fù)".format(user.email))
return reponse(data={'msg':"賬號不能重復(fù)"},code=1,message="error")
在使用的地方去引入,我們?nèi)蛹纯伞?/p>
啟動后,默認創(chuàng)建了這個文件
我們看下請求的輸出
而且在控制臺的輸出會根據(jù)你用的類型不一樣,對應(yīng)的日志的顏色也是不一樣的,我們看下文件的中的輸出
也是按照固定的格式給我們輸出的,還包含了我們是在哪一行輸出的,什么方法中,方便我們后續(xù)的排查問題。
代碼存儲https://gitee.com/liwanlei/fastapistuday
文章首發(fā)在公眾號,歡迎關(guān)注。
總結(jié)
以上是生活随笔為你收集整理的FastAPI 学习之路(六十)打造系统的日志输出的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ConcurrentDictionary
- 下一篇: oracle字符乱码的解决方法