Instrument a Python application
For most use cases Grafana Labs recommends Beyla, eBPF network-level auto-instrumentation, which is easy to set up and supports all languages and frameworks.
If you need process-level telemetry for Python, follow this documentation to set up the upstream OpenTelemetry SDK for Python for Application Observability.
Install the SDK
Before you begin ensure you have a Python 3 development environment and a Python application to instrument.
Run the following command in the project folder:
pip install "opentelemetry-distro[otlp]"
opentelemetry-bootstrap -a install
Instrument your application
Export the following environment variables before starting your application to enable auto-instrumentation:
export OTEL_PYTHON_LOGGING_AUTO_INSTRUMENTATION_ENABLED=true
export OTEL_LOGS_EXPORTER=otlp
Global Interpreter Lock
The OpenTelemetry Python SDK uses a Global Interpreter Lock (GIL) which can cause performance issues with web servers that spawn multiple processes to serve requests in parallel.
To fix this, register a post fork hook that is called after each worker process is forked.
The following code sample includes a post fork hook for Gunicorn:
Run the Gunicorn script using the following command gunicorn app -c gunicorn.conf.py
.
Note
To register a post for hook for other web servers, such as uWSGI, add the
@postfork
decorator to your hook function.
Test your instrumentation
To test if you’ve successfully instrumented your application, run your application, generate some traffic, and you should see metrics and logs outputted to the console.
opentelemetry-instrument flask run -p 8080
Example application
See the Rolldice service for a complete example setup.
Next steps
- Create a free Grafana Cloud account.
- For a local development and testing, send data to the Grafana Cloud OTLP endpoint.
- For production, set up an OpenTelemetry Collector.
- Observe your services in Application Observability.