> For the complete documentation index, see [llms.txt](https://doc.ozforensics.com/oz-knowledge-ru/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://doc.ozforensics.com/oz-knowledge-ru/rukovodstva/rukovodstvo-administratora/kak-vklyuchit-opentelemetry-v-oz-api.md).

# Как включить OpenTelemetry в Oz API

{% hint style="warning" %}
Для работы OpenTelemetry необходима версия API не ниже **6.6.1**.
{% endhint %}

Описанное ниже решение основано на [Python zero-code instrumentation](https://opentelemetry.io/docs/zero-code/python).

Oz API поддерживает только автоинструментацию **traces** — метрики и логи не поддерживаются.

Включение зависит от способа развёртывания — см. разделы Kubernetes и Docker ниже. Набор переменных окружения одинаков для обоих вариантов и приведён в разделе [Переменные окружения](#переменные-окружения).

Пример traces для Jaeger:

<figure><img src="https://2041336905-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FHLoHbtSPFA1Ul7oKM5SC%2Fuploads%2FpS8i9jZ4QB1HrQPv2m89%2FOz-API-trace-Jaeger.png?alt=media&amp;token=fb0e1b00-3fd9-45ee-bbe7-d93e592c41f4" alt=""><figcaption></figcaption></figure>

## Kubernetes

{% hint style="info" %}
Поддерживается с версии **oz-k8s/0.20.29**.
{% endhint %}

При включении `opentelemetry` чарт оборачивает процесс Oz API в `opentelemetry-instrument` и отправляет traces в OTLP-коллектор.

Включите автоинструментацию и укажите адрес коллектора. `OTEL_EXPORTER_OTLP_ENDPOINT` — единственная обязательная переменная:

```yaml
Params:
  gunicorn:
    opentelemetry:
      enable: true
    envs:
      OTEL_EXPORTER_OTLP_ENDPOINT: "http://otel-collector:4317"   # gRPC endpoint OTLP-коллектора
      OTEL_EXPORTER_OTLP_INSECURE: "true"                         # установите, если у коллектора нет TLS
```

Остальные переменные передаются так же через `Params.gunicorn.envs`.

## Docker

Для включения автоинструментации установите переменную окружения `OTEL_ENABLE=true` и укажите gRPC endpoint-коллектора в переменной `OTEL_EXPORTER_OTLP_ENDPOINT` при запуске контейнера:

```shell
docker run -e OTEL_ENABLE=true -e OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317 ...
```

Этого достаточно — traces начнут отправляться на указанный OTLP-коллектор по gRPC.

{% hint style="info" %}
Если `OTEL_ENABLE` не установлено в `true`, приложение запускается без обертки `opentelemetry-instrument`.
{% endhint %}

## Переменные окружения

Ниже представлены основные параметры конфигурации для варианта `OTEL_TRACES_EXPORTER=otlp`. Детальная информация по конфигурированию OTEL-агента размещена на сайте [OpenTelemetry](https://opentelemetry.io/docs/zero-code/python/configuration/).

<table data-header-hidden="false" data-header-sticky><thead><tr><th>Переменная</th><th>Описание</th><th>Значение по умолчанию</th></tr></thead><tbody><tr><td><code>OTEL_ENABLE</code></td><td><div data-gb-custom-block data-tag="hint" data-style="warning" class="hint hint-warning"><p><strong>Только для Docker.</strong></p></div><p>Включение OTEL-автоинструментации (<code>true</code> / не задано). При установке <code>true</code> запускает автоинструментацию OpenTelemetry через скрипт start.sh. Этот скрипт используется по умолчанию при запуске образа oz-api. Если при запуске контейнера вы переопределяете <code>ENTRYPOINT</code>, необходимо явно подставить запуск приложения с оберткой <code>opentelemetry-instrument</code>: <code>opentelemetry-instrument gunicorn oz_api.asgi:application &#x3C;...></code>. В Kubernetes-чарте эта переменная не используется — включение задаётся через <code>opentelemetry.enable: true</code>.</p></td><td>не задано (выключено)</td></tr><tr><td><code>OTEL_EXPORTER_OTLP_ENDPOINT</code></td><td>Адрес OTLP-коллектора</td><td>не задано (необходимо задать при включении)</td></tr><tr><td><code>OTEL_SERVICE_NAME</code></td><td>Имя сервиса в traces</td><td><code>oz-api.python.otel</code></td></tr><tr><td><code>OTEL_TRACES_EXPORTER</code></td><td><p>Экспортер traces. Возможные значения:</p><ul><li><code>otlp</code> — <a href="https://opentelemetry.io/docs/specs/otlp/">OTLP</a>;</li><li><code>jaeger</code> — export in Jaeger data model;</li><li><code>zipkin</code> — <a href="https://zipkin.io/zipkin-api/">Zipkin</a>;</li><li><code>console</code> — <a href="https://opentelemetry.io/docs/specs/otel/trace/sdk_exporters/stdout/">Standard Output</a>;</li><li><code>none</code> — не используются экспортеры с автоматической настройкой</li></ul></td><td><code>otlp</code></td></tr><tr><td><code>OTEL_EXPORTER_OTLP_PROTOCOL</code></td><td><p>Протокол экспорта. Возможные значения:</p><ul><li><code>grpc</code> для OTLP/gRPC;</li><li><code>http/protobuf</code> для OTLP/HTTP + <code>protobuf</code>;</li><li><code>http/json</code> для OTLP/HTTP + JSON</li></ul></td><td><code>grpc</code></td></tr><tr><td><code>OTEL_METRICS_EXPORTER</code></td><td>Экспортер метрик, не поддерживается</td><td><code>none</code></td></tr><tr><td><code>OTEL_LOGS_EXPORTER</code></td><td>Экспортер логов, не поддерживается</td><td><code>none</code></td></tr><tr><td><code>OTEL_PROPAGATORS</code></td><td><p>Форматы propagation context. Возможные значения:</p><ul><li><code>tracecontext</code> — <a href="https://www.w3.org/TR/trace-context/">W3C Trace Context</a>;</li><li><code>baggage</code> — <a href="https://www.w3.org/TR/baggage/">W3C Baggage</a>;</li><li><code>b3</code> — <a href="https://opentelemetry.io/docs/specs/otel/context/api-propagators/#configuration">B3 Single</a>;</li><li><code>b3multi</code> — <a href="https://opentelemetry.io/docs/specs/otel/context/api-propagators/#configuration">B3 Multi</a>;</li><li><code>jaeger</code> — <a href="https://www.jaegertracing.io/sdk-migration/">Jaeger</a>;</li><li><code>xray</code> — <a href="https://docs.aws.amazon.com/xray/latest/devguide/xray-concepts.html#xray-concepts-tracingheader">AWS X-Ray</a>;</li><li><code>ottrace</code> — <a href="https://github.com/opentracing?q=basic&#x26;type=&#x26;language=">OT Trace</a>;</li><li><code>none</code> — не используются пропагаторы с автоматической настройкой</li></ul></td><td><code>tracecontext,baggage</code></td></tr><tr><td><code>OTEL_PYTHON_DISABLED_INSTRUMENTATIONS</code></td><td>Отключенные авто-инструментации</td><td><code>psycopg2</code></td></tr><tr><td><code>OTEL_EXPORTER_OTLP_INSECURE</code></td><td>Отключение TLS для gRPC-вызова API OTLP-коллектора. Для эндпойнтов, не использующих шифрование TLS, установите <code>true</code>.</td><td>не задано (используется TLS)</td></tr></tbody></table>

## Примечания

* Автоинструментация `psycopg2` по умолчанию отключена, иначе собираемые данные могут быть избыточны. Детальные spans передаются через автоинструментацию `sqlalchemy`.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://doc.ozforensics.com/oz-knowledge-ru/rukovodstva/rukovodstvo-administratora/kak-vklyuchit-opentelemetry-v-oz-api.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
