• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

关于python:为-fastapi-添加请求id

python 搞代码 3年前 (2022-02-25) 16次浏览 已收录 0个评论

为了做日志跟踪,咱们能够用上面的方法来搞一个 request_id 或者说 correlation_id 的货色。

main.py

import sys
import uvicorn
import logging
from uuid import uuid4
from loguru import logger
from fastapi import FastAPI
from fastapi import Request
from typing import Optional
from contextvars import ContextVar


correlation_id: ContextVar[Optional[str]] = ContextVar(
    'correlation_id', default=None)

app = FastAPI()


@app.middleware("http")
async def add_request_id_header(request: Request, call_next):
    correlation_id.set(uuid4().hex)
    response = await call_next(request)

    response.headers["x-request-id"] = correlation_id.get()
    return response


logger.remove()


def correlation_id_filter(record):
    record['correlation_id'] = correlation_id.get()
    return record['correlation_id']


fmt = "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | <level>{level: <8}</level> | <red> {correlation_id} </red> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>"


logger.add(sys.stderr, format=fmt, level=logging.DEBUG,
           filter=correlation_id_filter)


@app.get('/')
def index():
    logger.info(f"Request with id ")
    return 'OK'


if __name__ == "__main__":
    uvicorn.run(app="main:app", host="0.0.0.0", port=8000)

应用上面的命令运行程序:

<code class="shell">python main.py

用上面的命令发动 http 申请来做测试

<code class="shell">http http://localhost:8000/  -v

能够应用 apt install httpie 或者 brew install httpie 来装置 http 命令

输入如下:

<code class="shell">GET / HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Host: localhost:8000
User-Agent: HTTPie/2.6.0



HTTP/1.1 200 OK
content-length: 4
content-type: application/json
date: Mon, 21 Feb 2022 13:36:50 GMT
server: uvicorn
x-request-id: a27b3b26382545e9ae15358a321a9568

"OK"

事实上,曾经有相应的开源实现了:snok/asgi-correlation-id


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:关于python:为-fastapi-添加请求id
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址