当前位置: 首页 > 后端技术 > Python

为fastapi添加全局唯一请求id,用于日志跟踪

时间:2023-03-25 21:51:50 Python

为了做日志跟踪,我们可以使用下面的方法创建一个request_id或correlation_id。main.pyimportsysimportuvicornimportloggingfromuuidimportuuid4fromloguruimportloggerfromfastapiimportFastAPIfromfastapiimportRequestfromtypingimportOptionalfromcontextvarsimportContextVarcorrelation_id:ContextVar[Optional[str]]=ContextVar('correl=Fast_app,'correlation).middleware("http")复制代码asyncdefadd_request_id_header(request:Request,call_next):correlation_id.set(uuid4().hex)response=awaitcall_next(request)response.headers["x-request-id"]=correlation_id.get()返回responselogger.remove()defcorrelation_id_filter(record):record['correlation_id']=correlation_id.get()returnrecord['correlation_id']fmt="{time:YYYY-MM-DDHH:mm:ss.SSS}|{level:<8}|{correlation_id}|{name}:>{function}:{line}-{message}"logger.add(sys.stderr,format=fmt,level=logging.DEBUG,filter=correlation_id_filter)@app.get('/')defindex():logger.info(f"Requestwithid")return'OK'if__name__=="__main__":uvicorn.run(app="main:app",host="0.0.0.0",port=8000)使用如下命令运行程序:pythonmain.py使用以下命令发起http请求,用于测试http://localhost:8000/-v你可以使用aptinstallhttpie或者brewinstallhttpie安装http命令输出如下:GET/HTTP/1.1Accept:*/*Accept-Encoding:gzip,deflateConnection:keep-aliveHost:localhost:8000User-Agent:HTTPie/2.6.0HTTP/1.1200OKcontent-length:4content-type:application/jsondate:Mon,21Feb202213:36:50GMTserver:uvicornx-request-id:a27b3b26382545e9ae15358a321a9568"OK"其实已经有对应的开源实现:snok/asgi-correlation-id参考文章:FastAPI入门系列中的中间件!