首页 > 编程问答 >Sanic 中的 Prometheus 指标

Sanic 中的 Prometheus 指标

时间:2024-08-06 15:56:49浏览次数:5  
标签:python prometheus metrics asgi sanic

我正在尝试向我的 Sanic 应用程序添加指标。 Prometheus 提供作为 ASGI 应用程序运行的 Python 客户端 - https://prometheus.github.io/client_python/exporting/http/asgi/ .

问题是如何同时运行 2 个 ASGI 应用程序。| ||我发现 Starlette 可以提供帮助:

安装并工作, 但 Sunic 返回一个异常:

from prometheus_client import make_asgi_app
from starlette.applications import Starlette
from starlette.routing import Mount
from sanic import Sanic
from sanic.response import text

sanic_app = Sanic("MyHelloWorldApp")

@sanic_app.get("/")
async def hello_world(request):
    return text("Hello, world.")

metrics_app = make_asgi_app()

routes = [
    Mount("/", app=sanic_app),
    Mount("/metrics", app=metrics_app)
]

app = Starlette(routes=routes)

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000, log_level="info")

metrics_app 有人知道将 Prometheus 客户端与 ASGI Sanic 一起使用的更直接的方法吗?

sanic.exceptions.SanicException: Loop can only be retrieved after the app has started running. Not supported with `create_server` function

Does anybody know a more straightforward way to use Prometheus Client with ASGI Sanic?


遇到的错误是因为 Sanic 没有以 ASGI 应用的方式运行。虽然 Sanic 可以使用 uvicorn 运行,但这会在其上创建一个 ASGI 层,而 Sanic 本身并不了解它。

要解决这个问题,需要直接在 Sanic 中公开 Prometheus 指标端点,而不是尝试将其作为单独的 ASGI 应用程序运行。

以下是如何操作:

import asyncio

from prometheus_client import Counter, generate_latest
from sanic import Sanic
from sanic.response import raw, text

app = Sanic("MyHelloWorldApp")

# 创建一个简单的计数器指标
REQUEST_COUNT = Counter(
    'request_count',
    'Total number of requests served',
    ['method', 'endpoint']
)

@app.route("/")
async def hello_world(request):
    REQUEST_COUNT.labels(request.method, request.path).inc()
    return text("Hello, world.")

@app.route("/metrics")
async def metrics(request):
  # 使用 asyncio.to_thread 将同步函数转换为异步函数
  # generate_latest 是同步函数,需要在单独的线程中执行
  content = await asyncio.to_thread(generate_latest) 
  return raw(content, content_type="text/plain; version=0.0.4; charset=utf-8")

if __name__ == "__main__":
    app.run(host="127.0.0.1", port=8000)

这段代码执行以下操作:

  1. 定义指标: 创建一个 REQUEST_COUNT 计数器,用于跟踪每个端点的请求数量及其 HTTP 方法。
  2. 增加指标: hello_world 处理程序中,使用 REQUEST_COUNT.labels().inc() 增加相应标签的计数器。
  3. 公开指标端点: 创建一个新的 /metrics 路由,该路由使用 generate_latest 函数以 Prometheus 格式返回指标。
  4. 运行 Sanic 应用: 与以前一样启动 Sanic 应用。

现在,应该能够访问 http://127.0.0.1:8000/metrics 并查看 Prometheus 格式的指标。

请记住,这只是一个简单的示例,可以根据自己的需要定义更复杂的指标和标签。

标签:python,prometheus,metrics,asgi,sanic
From: 78837870

相关文章

  • python SQLite 访问组件
    importosimportsqlite3fromsqlite3importErrorfromqueueimportQueue,EmptyfromtypingimportList,Tuple,AnyclassSQLiteDB:default_db_path=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))default_db_file=default_db_path......
  • Python 卡在第 1 页
    让它读取下一页结果的最佳方法是什么?目前正在拉取数据,但只有第1页importrequestsimportjsonpage=1url="https://api-prod.grip.events/1/container/4368/search?search=&sort=name&order=asc&type_id=4907,4906,5265,4964,4904,1026,4908&page=%d"headers={......
  • 无法反序列化解码 JWT python 时的关键数据
    我正在使用pyjwt库来解码JWT令牌。我在解码时遇到此错误。代码在文档中给出。importjwtencoded_jwt='''eyJ0eXAiOiJKV1QiLCJhbG......'''secret=b''''-----BEGINPUBLICKEY-----MIIFRjCCBC6gAwIBAgIQCIdSGhpikQCjOIY154XoqzANBgkqhkiG9......
  • Python科研武器库 - 字符串操作 - 字符串开头结尾判断 startswith() endswith()
    使用场景:按照开头的前缀、结尾的后缀来判断、筛选目标字符串。使用函数:str.startswith(search_string,start,end)str.endswith(search_string,start,end)search_string:要匹配的目标字符串。start:要从中匹配search_string的str的起始索引。end:要考虑匹配的str的结......
  • 我正在 python 中使用 aspose.pdf 将 pdf 转换为 excel 。但问题是它只能将 pdf 的前
    `从tkinter导入*将aspose.pdf导入为ap从tkinter导入文件对话框importpandasaspdinput_pdf=filedialog.askopenfilename(filetypes=(("PDF文件",".pdf"),("所有文件",".")))output_file=filedialog.asksaveasfil......
  • 如何在selenium python中访问电子邮件中的所有文件夹
    我使用imaplib库,但有时无法访问某些帐户,我使用poplib但它只支持访问主邮箱,但不支持访问其他文件夹,如垃圾邮件我想使用imaplib,但不会出现有时甚至无法访问的错误尽管我有一个帐户,但我仍然可以访问它,或者是否有另一个库可以快速支持该帐户?你想要使用Selenium和Python......
  • python安装torch-cluster、torch-scatter、torch-sparse和torch-geometric | torch_ge
    1.检查CUDA版本【方法1】用nvidia-smi已装cuda,用nvidia-smi或nvcc-V查看【方法2】用torch已装torch,用torch代码打印importtorchprint(torch.__version__)#查看pytorch安装的版本号print(torch.cuda.is_available())#查看cuda是否可......
  • Python:学生成绩管理系统(大学编程期末实验)
    引言在这个信息时代,教育管理的自动化已成为提高效率的关键。本文将介绍如何使用Python开发一个学生成绩管理系统,旨在简化成绩记录、查询和分析的过程。创作灵感来源本项目灵感来源于我在教育机构的工作经历,以及对提高教育管理效率的持续追求。通过复盘过往项目,我意识到一个......
  • 手把手教你使用Python网络爬虫下载一本小说(附源码)
    大家好,我是Python进阶者。前言前几天【磐奚鸟】大佬在群里分享了一个抓取小说的代码,感觉还是蛮不错的,这里分享给大家学习。一、小说下载如果你想下载该网站上的任意一本小说的话,直接点击链接进去,如下图所示。只要将URL中的这个数字拿到就可以了,比方说这里是951,那么这个数字......
  • 借助 Transformer 实现美股价格的预测(Python干货)
    作者:老余捞鱼原创不易,转载请标明出处及原作者。写在前面的话:      Transformer是一种在自然语言处理等领域广泛应用的深度学习架构,与传统的循环神经网络(RNN)相比,Transformer可以并行处理输入序列的各个位置,大大提高了计算效率。而且通过多层的深度堆叠,能够学习......