Monitoring Django WebApps with Prometheus

thecolossus

Fife Oluwabunmi

Posted on August 27, 2024

Monitoring Django WebApps with Prometheus

In the previous article, we looked at how to setup Prometheus and we got a feel of what it looks like to monitor a service. In this one, we'll be going straight into monitoring applications- Django Web apps, so if you're trying to figure out how to up your observability game, this article is for you!

Let's get into it!

Prerequisite

  • Prometheus installed

  • Basic understanding of how Prometheus works (Check my previous article)

  • A functioning Django application you want to monitor.

Something you should keep in mind: Prometheus monitors applications through client libraries. Read the docs.

In this article, we'll be using django-prometheus to export the metrics of our Django App to Prometheus!

Installing and setting up django-prometheus



pip install django-prometheus


Enter fullscreen mode Exit fullscreen mode

In your settings.py, add the following:



INSTALLED_APPS = [
   ...
   'django_prometheus',
   ...
]

MIDDLEWARE = [
    'django_prometheus.middleware.PrometheusBeforeMiddleware',
    .
    .
    .
    'django_prometheus.middleware.PrometheusAfterMiddleware',
]


Enter fullscreen mode Exit fullscreen mode

In the urls.py of your Django project:



urlpatterns = [
    ...
    path('', include('django_prometheus.urls')),
]


Enter fullscreen mode Exit fullscreen mode

Note:

  1. This should be added in the urls.py of your Django project and NOT the Django app. Please review this article.

  2. For more details on the django-prometheus package, read here.

  3. Be sure to update your requirements.txt file



pip freeze > requirements.txt


Enter fullscreen mode Exit fullscreen mode

Next, update your prometheus.yml file to look like this:



global:
  scrape_interval:     5s
  evaluation_interval: 5s

alerting:
  alertmanagers:

scrape_configs:
  - job_name: 'django-app'
    static_configs:
      - targets: ['127.0.0.1:8000']
        labels:
          group: 'server'



Enter fullscreen mode Exit fullscreen mode

NOTE: If this section is unclear, refer to my previous article

Start your webserver and open 127.0.0.1:8000/metrics. You should have output like this:

Django app metrics

To be able to access the Prometheus UI, start up your Prometheus server with this command



./prometheus --config.file=prometheus.yml
# Make sure you're in the prometheus-2.54.0.darwin-amd64 dir
# The name will vary depending on your OS/distribution ;)


Enter fullscreen mode Exit fullscreen mode

You can now run queries in the Prometheus UI at http://127.0.0.1:9090/.

In the next one, we'll look at scraping custom metrics from our applications!

Cheers!

💖 💪 🙅 🚩
thecolossus
Fife Oluwabunmi

Posted on August 27, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Monitoring Django WebApps with Prometheus