0

I'm trying to add metrics to my Sanic app. Prometheus provides Python client running as ASGI app - https://prometheus.github.io/client_python/exporting/http/asgi/ .

The question is how to run 2 ASGI apps at once.

I found Starlette could help:

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 mounted and works, but Sunic returns an exception:

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?

asked Aug 6, 2024 at 7:58

1 Answer 1

0

I've just read https://pyk.medium.com/a-guide-to-instrument-sanic-application-part-1-193b3eb403a

The next works!

import prometheus_client as prometheus
@app.get("/metrics")
async def metrics(request):
 return text(prometheus.exposition.generate_latest().decode("utf-8"))
answered Aug 6, 2024 at 8:38
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.