# Instrumenting Django with OpenTelemetry

# Prerequisites

  • Python 3.6+

# Introduction

In this tutorial we will instrument a basicopen in new window Django app using OpenTelemetry instrumentation.

# Instrumenting Django app

  • Step 1. Let's start by downloading the source code:
git clone https://github.com/uptrace/uptrace-python.git
cd example/django
1
2
  • Step 2. Install the required dependencies:
pip install -r requirements.txt
1
  • Step 3. Edit manage.py to configure OpenTelemetry to export data to Uptrace:
import uptrace

def main():
    uptrace.configure_opentelemetry(
        # Copy DSN here or use UPTRACE_DSN env var.
        dsn="",
    )
1
2
3
4
5
6
7
  • Step 4. Edit manage.py to instrument the Django app:
from opentelemetry.instrumentation.django import DjangoInstrumentor

def main():
    # DjangoInstrumentor uses DJANGO_SETTINGS_MODULE to instrument the app. Make sure to define it.
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app_name.settings")

    # Instrument the app by adding middleware etc.
    DjangoInstrumentor().instrument()

    ...
1
2
3
4
5
6
7
8
9
10
UPTRACE_DSN="https://<token>@api.uptrace.dev/<project_id>" ./manage.py runserver
1

The full code is available at GitHubopen in new window.

# What is next?

By now, you should have a Django app with instrumented views. Next, instrumentopen in new window more operations (for example, database queries) or learn about OpenTelemetry API to create your own instrumentations.