實現方式:
采用 loguru 模塊、跟flask直接掛載到app上有區別,當然也可以嘗試去這樣做、
但是 好像沒有這個必要、要的就是個快速、整那些子虛烏有的東西完全木有意義。
1、首先是去項目git溜達一圈:https://github.com/Delgan/loguru
發現是英文。。。 木得感情、
然后百度百度吧,還好python大神們都挺友好。
百度一下 :python loguru 。。問題解決
https://www.cnblogs.com/g2thend/p/12539923.html
https://www.cnblogs.com/ice-coder/p/12821326.html
2、首先肯定是模塊安裝了
pip install loguru
3、結合到FastAPI 項目、其實老簡單了。
1)搞個單獨的日志管理模塊
2)日志內容配置
3)項目模塊引用、完活 !!!
1)日志配置模塊: 創建extensions\logger.py,什么位置/名稱的無所謂、只要能夠被引用就行
2)配置日志內容 : 應該都能看懂、看不懂自己百度去吧。
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) if not os.path.exists(log_path): os.mkdir(log_path) log_path_all = os.path.join(log_path, f'{time.strftime("%Y-%m-%d")}_log.log') 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_all, rotation="12:00", retention="5 days", enqueue=True) logger.add(log_path_error, rotation="12:00", retention="5 days", enqueue=True,level='ERROR') # 日志等級分割 # format 參數: {time} {level} {message}、 {time:YYYY-MM-DD at HH:mm:ss} | {level} | {message} 記錄參數 # level 日志等級 # rotation 參數:1 week 一周、00:00每天固定時間、 500 MB 固定文件大小 # retention 參數: 10 days 日志最長保存時間 # compression 參數: zip 日志文件壓縮格式 # enqueue 參數 True 日志文件異步寫入 # serialize 參數: True 序列化json # encoding 參數: utf-8 字符編碼、部分情況會出現中文亂碼問題 # logger.info('If you are using Python {}, prefer {feature} of course!', 3.6, feature='f-strings') 格式化輸入內容 # 可通過等級不同對日志文件進行分割儲存
3)項目模塊引用:
from fastapi import FastAPI,Form,Query,UploadFile,File,Request from pydantic import BaseModel,Field from typing import Optional,List import os,sys,time from extensions.logger import logger ''' 虛擬環境切換: conda activate FastAPI FastAPI 程序啟動 :uvicorn manger:app --port 7777 --reload ''' app = FastAPI() @logger.catch # 異常記錄裝飾器、放到下面好像不行、應該是異步的關系。 def my_function(x, y, z): return [x,y,z] @app.post('/') async def root(data:dict): # get 請求 logger.debug(f"這是日志!") logger.info('這是user接口:username={},當前時間戳為:{tiems}',data["username"], tiems=time.time()) my_function(0,0) return {'message':'Hello World!'}
完活!!!!
太特么簡單了,有木有、