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?
1 Answer 1
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"))
Comments
Explore related questions
See similar questions with these tags.