OpenTelemetry Django Instrumentation Example

This shows how to use opentelemetry-instrumentation-django to automatically instrument a Django app.

For more user convenience, a Django app is already provided in this directory.

Preparation

This example will be executed in a separate virtual environment:

$ mkdir django_auto_instrumentation
$ virtualenv django_auto_instrumentation
$ source django_auto_instrumentation/bin/activate

Installation

$ pip install opentelemetry-sdk
$ pip install opentelemetry-instrumentation-django
$ pip install requests

Execution

Execution of the Django app

Set these environment variables first:

  1. export DJANGO_SETTINGS_MODULE=instrumentation_example.settings

The way to achieve OpenTelemetry instrumentation for your Django app is to use an opentelemetry.instrumentation.django.DjangoInstrumentor to instrument the app.

Clone the opentelemetry-python repository and go to opentelemetry-python/docs/examples/django.

Once there, open the manage.py file. The call to DjangoInstrumentor().instrument() in main is all that is needed to make the app be instrumented.

Run the Django app with python manage.py runserver.

Execution of the client

Open up a new console and activate the previous virtual environment there too:

source django_auto_instrumentation/bin/activate

Go to opentelemetry-python/docs/examples/django, once there run the client with:

python client.py hello

Go to the previous console, where the Django app is running. You should see output similar to this one:

{
    "name": "home_page_view",
    "context": {
        "trace_id": "0xed88755c56d95d05a506f5f70e7849b9",
        "span_id": "0x0a94c7a60e0650d5",
        "trace_state": "{}"
    },
    "kind": "SpanKind.SERVER",
    "parent_id": "0x3096ef92e621c22d",
    "start_time": "2020-04-26T01:49:57.205833Z",
    "end_time": "2020-04-26T01:49:57.206214Z",
    "status": {
        "status_code": "OK"
    },
    "attributes": {
        "component": "http",
        "http.method": "GET",
        "http.server_name": "localhost",
        "http.scheme": "http",
        "host.port": 8000,
        "http.host": "localhost:8000",
        "http.url": "http://localhost:8000/?param=hello",
        "net.peer.ip": "127.0.0.1",
        "http.flavor": "1.1",
        "http.status_text": "OK",
        "http.status_code": 200
    },
    "events": [],
    "links": []
}

The last output shows spans automatically generated by the OpenTelemetry Django Instrumentation package.

Disabling Django Instrumentation

Django’s instrumentation can be disabled by setting the following environment variable.

  1. export OTEL_PYTHON_DJANGO_INSTRUMENT=False