> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Zero Code Instrumentation in Python

> Explains OpenTelemetry Python zero-code auto-instrumentation using monkey patching to capture traces and metrics for common libraries, plus installation, configuration, and debugging steps.

Zero-code (or auto-) instrumentation lets you add observability to Python applications without modifying source code. In Python this is achieved primarily via monkey patching: at runtime, the agent replaces or wraps existing functions and methods in popular libraries so that traces and metrics are collected automatically. While other languages (like Java) commonly use bytecode manipulation, Python’s runtime patching delivers the same outcome by altering call behavior as the program runs.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/OYg0ei_WZpJtYDrJ/images/Prep-Course-OpenTelemetry-Certified-Associate-OTCA-Certification/Instrumentation/Zero-Code-Instrumentation-in-Python/monkey-patching-basics-instrumentation-diagram.jpg?fit=max&auto=format&n=OYg0ei_WZpJtYDrJ&q=85&s=f3559211d68f6aa7ece72d43474fbe7e" alt="The image explains monkey patching basics for instrumentation, highlighting two points: modifying existing methods at runtime and injecting logic into libraries without altering their source code." width="1920" height="1080" data-path="images/Prep-Course-OpenTelemetry-Certified-Associate-OTCA-Certification/Instrumentation/Zero-Code-Instrumentation-in-Python/monkey-patching-basics-instrumentation-diagram.jpg" />
</Frame>

OpenTelemetry for Python provides auto-instrumentation for many widely used libraries and frameworks (Flask, Django, Requests, SQLAlchemy, Redis, etc.), making it simple to gain observability with zero code changes. See the official docs: [OpenTelemetry for Python](https://opentelemetry.io/docs/instrumentation/python/).

How zero-code instrumentation works (high level)

1. The OpenTelemetry agent applies monkey patches to supported libraries at runtime.
2. Patches wrap or modify library functions so requests, DB queries, and messaging calls generate spans and metrics automatically.
3. If your app uses supported libraries, traces and metrics appear with no manual SDK calls.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/OYg0ei_WZpJtYDrJ/images/Prep-Course-OpenTelemetry-Certified-Associate-OTCA-Certification/Instrumentation/Zero-Code-Instrumentation-in-Python/zero-code-instrumentation-python-explained.jpg?fit=max&auto=format&n=OYg0ei_WZpJtYDrJ&q=85&s=3cb3ddd9db5f9f142d2189759cb47781" alt="The image explains how zero-code instrumentation operates in Python, highlighting four points: using monkey patching, modifying library functions at runtime, supporting various libraries, and eliminating the need for manual instrumentation." width="1920" height="1080" data-path="images/Prep-Course-OpenTelemetry-Certified-Associate-OTCA-Certification/Instrumentation/Zero-Code-Instrumentation-in-Python/zero-code-instrumentation-python-explained.jpg" />
</Frame>

## Installation

Install the OpenTelemetry distro and supporting packages, then let the bootstrap tool detect and install instrumentations for the dependencies in your environment.

```bash theme={null}
pip install opentelemetry-distro opentelemetry-exporter-otlp opentelemetry-instrumentation opentelemetry-bootstrap
opentelemetry-bootstrap -a install
```

The bootstrap step scans installed packages and adds relevant instrumentation libraries. After this, you can run the OpenTelemetry Python agent.

## Running the agent

Start your app with the `opentelemetry-instrument` wrapper to enable auto-instrumentation. Example that exports traces and metrics to the console (for development) and to an OTLP endpoint (typical for sending to an OTel Collector):

```bash theme={null}
opentelemetry-instrument \
  --traces_exporter console,otlp \
  --metrics_exporter console \
  --service_name your-service-name \
  --exporter_otlp_endpoint 0.0.0.0:4317 \
  python myapp.py
```

<Callout icon="lightbulb" color="#1CB2FE">
  For production, send telemetry to an OTLP Collector or backend instead of the console. Use the console exporter only for quick testing or troubleshooting.
</Callout>

## Configuration via environment variables

Environment variables are commonly used in containers and CI/CD pipelines. They provide the same control as CLI flags and are typically easier to manage in deployments.

Example environment variables:

```bash theme={null}
export OTEL_SERVICE_NAME=your-service-name
export OTEL_TRACES_EXPORTER=console,otlp
export OTEL_METRICS_EXPORTER=console
export OTEL_EXPORTER_OTLP_ENDPOINT=0.0.0.0:4317
```

Then start the instrumented process:

```bash theme={null}
opentelemetry-instrument python myapp.py
```

Python-specific configuration examples

```bash theme={null}
# Exclude health/metrics endpoints from tracing
export OTEL_PYTHON_EXCLUDED_URLS="/health,/metrics"

# Trace specific Django request attributes
export OTEL_PYTHON_DJANGO_TRACED_REQUEST_ATTRS="path_info,content_type"

# Enable log correlation and format logs to include trace/span ids
export OTEL_PYTHON_LOG_CORRELATION=true
export OTEL_PYTHON_LOG_FORMAT="%(msg)s [trace_id=%(trace_id)s span_id=%(span_id)s]"
export OTEL_PYTHON_LOG_LEVEL=debug

# Disable specific auto-instrumentations when needed
export OTEL_PYTHON_DISABLED_INSTRUMENTATIONS=redis,grpc,kafka
```

You can control sampling, exporters, and many other settings via environment variables—most are consistent across languages, with some Python-only options shown above.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/OYg0ei_WZpJtYDrJ/images/Prep-Course-OpenTelemetry-Certified-Associate-OTCA-Certification/Instrumentation/Zero-Code-Instrumentation-in-Python/opentelemetry-agent-settings-tutorial.jpg?fit=max&auto=format&n=OYg0ei_WZpJtYDrJ&q=85&s=a6f392f557df056eb77fe29042122a27" alt="The image shows a list of OpenTelemetry agent settings with their descriptions, including service name, traces exporter, metrics exporter, and endpoint details. It appears to be from a tutorial or guide by KodeKloud." width="1920" height="1080" data-path="images/Prep-Course-OpenTelemetry-Certified-Associate-OTCA-Certification/Instrumentation/Zero-Code-Instrumentation-in-Python/opentelemetry-agent-settings-tutorial.jpg" />
</Frame>

## Supported libraries (auto-instrumentation)

OpenTelemetry Python provides many built-in instrumentations and community-contributed packages. Typical coverage includes web frameworks, HTTP clients, database libraries, and messaging systems.

|               Category | Examples                                     |
| ---------------------: | -------------------------------------------- |
|         Web frameworks | Flask, Django, FastAPI, Starlette            |
|           HTTP clients | `requests`, `urllib3`                        |
|              Databases | SQLAlchemy and DB drivers (e.g., `psycopg2`) |
| Messaging & Background | Kafka, Celery                                |

This coverage gives immediate visibility across web requests, outbound HTTP calls, DB queries, and messaging layers.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/OYg0ei_WZpJtYDrJ/images/Prep-Course-OpenTelemetry-Certified-Associate-OTCA-Certification/Instrumentation/Zero-Code-Instrumentation-in-Python/popular-libraries-instrumentation-web-db-messaging.jpg?fit=max&auto=format&n=OYg0ei_WZpJtYDrJ&q=85&s=4067690469a029d14d576503f6d81f8c" alt="The image lists popular libraries with built-in instrumentation categorized as Web, HTTP, DB, and Messaging, featuring Flask, Django, FastAPI, Starlette, urllib3, SQLAlchemy, psycopg2, Kafka, and Celery." width="1920" height="1080" data-path="images/Prep-Course-OpenTelemetry-Certified-Associate-OTCA-Certification/Instrumentation/Zero-Code-Instrumentation-in-Python/popular-libraries-instrumentation-web-db-messaging.jpg" />
</Frame>

## Debugging automatic instrumentation

If a library isn’t being instrumented or spans/attributes are missing, enable debug logging to see detailed messages about what instrumentations are applied and any errors:

```bash theme={null}
export OTEL_LOG_LEVEL=debug
export OTEL_PYTHON_LOG_LEVEL=debug
```

Run your app under the instrument wrapper and inspect logs to identify missing hooks, import order issues, or conflicts between instrumentations.

## Repository & documentation

Key resources:

* Instrumentation libraries and contrib repo: [https://github.com/open-telemetry/opentelemetry-python-contrib](https://github.com/open-telemetry/opentelemetry-python-contrib)
* Auto-instrumentation CLI docs: [https://opentelemetry.io/docs/instrumentation/python/auto-instrumentation/](https://opentelemetry.io/docs/instrumentation/python/auto-instrumentation/)
* PyPI instrumentation package: [https://pypi.org/project/opentelemetry-instrumentation/](https://pypi.org/project/opentelemetry-instrumentation/)
* SDK configuration docs: [https://opentelemetry.io/docs/reference/specification/sdk-configuration/](https://opentelemetry.io/docs/reference/specification/sdk-configuration/)

Useful commands referenced in docs:

```text theme={null}
opentelemetry-bootstrap [-a|--action=][install|requirements]
opentelemetry-instrument python program.py
```

Installation via pip examples:

```bash theme={null}
pip install opentelemetry-instrumentation
pip install opentelemetry-distro opentelemetry-exporter-otlp
```

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/OYg0ei_WZpJtYDrJ/images/Prep-Course-OpenTelemetry-Certified-Associate-OTCA-Certification/Instrumentation/Zero-Code-Instrumentation-in-Python/general-sdk-configuration-opentelemetry.jpg?fit=max&auto=format&n=OYg0ei_WZpJtYDrJ&q=85&s=015614242cb57ef8e4a0b16e2b02813d" alt="The image shows a documentation page for &#x22;General SDK Configuration&#x22; in OpenTelemetry, detailing configuration settings like OTEL_SDK_DISABLED and OTEL_ENTITIES with descriptions, default values, and notes. The page includes a navigation sidebar and various configuration details for developers." width="1920" height="1080" data-path="images/Prep-Course-OpenTelemetry-Certified-Associate-OTCA-Certification/Instrumentation/Zero-Code-Instrumentation-in-Python/general-sdk-configuration-opentelemetry.jpg" />
</Frame>

## Python vs Java (brief comparison)

| Topic                  | Python (auto-instrumentation)                                                 | Java (javaagent)                                                        |
| ---------------------- | ----------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| Mechanism              | Monkey patching — wrap/replace functions at runtime                           | Bytecode instrumentation — modify classes at JVM startup (`-javaagent`) |
| Tooling                | `opentelemetry-instrument`, `opentelemetry-distro`, `opentelemetry-bootstrap` | `opentelemetry-javaagent.jar`                                           |
| Configuration          | CLI flags or environment variables (e.g., `OTEL_*`, `OTEL_PYTHON_*`)          | JVM agent flags and environment variables                               |
| Manual instrumentation | Optional via SDK APIs for custom spans                                        | Optional via SDK APIs for custom spans                                  |
| Log correlation        | `OTEL_PYTHON_LOG_CORRELATION=true` and log formatter support                  | Supported via JVM logging frameworks and agent config                   |

## Summary

OpenTelemetry Python zero-code instrumentation (auto-instrumentation) provides immediate observability for many common libraries without modifying application source code. Workflow summary:

1. Install distro + exporters + instrumentation packages.
2. Run `opentelemetry-bootstrap -a install` to add relevant instrumentations.
3. Start your app with `opentelemetry-instrument` or use equivalent environment variables.
4. Tune Python-specific options (exclusions, log correlation, disabled instrumentations) as needed.

These steps let you quickly capture telemetry (traces and metrics) across web, HTTP client, DB, and messaging layers with minimal operational overhead.

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/prep-course-opentelemetry-certified-associate-certification-otca/module/d97970ef-6201-45c2-813e-e03bc75ad77a/lesson/712825de-6ca0-4b88-8032-9a1f628f5560" />
</CardGroup>
