How to export app metrics using prometheus client from an Django app running as an uwsgi server?

Viewed 2859

I read the docs of prometheus client https://github.com/prometheus/client_python/#multiprocess-mode-gunicorn where it mentions to expose metrics in a multi-process mode in python. Instead of Gunicorn, I am running django app via uwsgi. Similar to that in the docs I added code in my project's wsgi.py -

class WSGIEnvironment(WSGIHandler):
def __call__(self, environ, start_response):

    **registry = CollectorRegistry()
    multiprocess.MultiProcessCollector(registry)
    data = generate_latest(registry)**
    django.setup()
    return super(WSGIEnvironment, self).__call__(environ, 
    start_response)
application = WSGIEnvironment()

But exposing collected data via this method did not look feasible to me. Hence I exposed an api in my Django app /metrics which invokes metrics view -

def metrics(request):

    registry = CollectorRegistry()
    multiprocess.MultiProcessCollector(registry)
    data = generate_latest(registry)
    print "data", data
    return HttpResponse(
        data,
        content_type=CONTENT_TYPE_LATEST)

Still I cannot view the metrics being exposed by my app. Is there any configuration required? I think I am missing very basic thing.

1 Answers

That looks indeed quite good. I've got it working in a similar way, by just creating a view (exactly like you posted it) and without modifying the wsgi.py.

The /metrics view will serve an empty page if there are no metrics found. If you see an empty page, there might be something wrong recording the metrics. If you see a 404, then there is something wrong with your urls.py.

One common mistake is to call a counter without increasing it:

# right
my_counter.labels(my_label='a').inc()

# wrong
my_counter.labels(my_label='a')

Hope that helps.

Related