К основному содержанию
скилл CX Codex

otel-ottl — скилл для Claude Code: что делает и как установить

Помогает писать и отлаживать выражения OTTL для компонентов OpenTelemetry Collector. Пригодится при фильтрации трейсов, маскировании данных и маршрутизации телеметрии.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add dash0hq/agent-skills --skill otel-ottl -a claude-code
Открыть на GitHub

Что делает otel-ottl

Скилл содержит справочник по синтаксису OpenTelemetry Transformation Language (OTTL) для процессоров и коннекторов Collector. Он подсказывает агенту правила обращения к путям телеметрии через контексты span, log, metric, datapoint или resource. Синтаксис строго разделяет функции: конвертеры вроде ToUpperCase или Substring пишутся заглавными буквами и возвращают значение, а редакторы вроде set и delete_key пишутся строчными и меняют данные на месте.

В базу заложены типичные сценарии: обогащение атрибутами, удаление чувствительных полей, отсечение устаревших данных и нормализация путей для снижения кардинальности. Проверка отсутствия поля требует именно nil, а не привычный null. Неверный синтаксис приведёт к ошибке компиляции ещё при старте коллектора, поэтому перед запуском требуется проверять конфигурацию через команду otelcol validate --config=config.yaml.

Параметр error_mode критичен в продакшене. Если в процессорах transform и filter начиная с версии Contrib v0.153.0 по умолчанию стоит ignore, то коннекторы routing и signaltometrics по умолчанию сбрасывают весь пакет при первой же ошибке.

Какие задачи решает

  • нормализовать URL и пути запросов для борьбы с высокой кардинальностью метрик
  • замаскировать или удалить конфиденциальные данные в логах и спанах
  • настроить условия фильтрации телеметрии через предикаты where
  • подготовить конфигурацию процессора transform с обработкой ошибок error_mode: ignore
  • проверить отсутствие атрибута с помощью проверки на nil

Примеры запросов агенту

  • Помоги написать выражение OTTL для маскирования db.statement в процессоре transform
  • Как через OTTL удалить ключ internal.key из resource.attributes, если он существует?
  • Собери фильтр для filter processor, который отбрасывает спаны со статусом STATUS_CODE_ERROR

Как установить otel-ottl

1Через Skills CLI (Vercel)

npx skills add dash0hq/agent-skills --skill otel-ottl -a claude-code

2Вручную: положить файлы

~/.claude/skills/otel-ottl/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/otel-ottl/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Из того же набора3

Похожие

otel-instrumentation honeycombio Ставит OpenTelemetry SDK, добавляет кастомные спаны и атрибуты и отправляет данные в Honeycomb. Пригодится, когда нужно разобраться, где именно тормозит запрос. CX Codex +1 3 600установок logfire-query pydantic Выполняет SQL-запросы к телеметрии Logfire прямо через агента. Скилл нужен для поиска медленных спанов, группировки исключений и расчёта метрик. CX Codex +1 1 900установок observability-and-instrumentation addyosmani Скилл учит агента добавлять структурированные логи, метрики и трейсы в код до деплоя. Пригодится при выпуске новых эндпоинтов, фоновых задач и интеграций. CX Codex +1 54 800установок opentelemetry grafana Скилл помогает подключить OpenTelemetry к приложению и отправить метрики, логи и трейсы в Grafana Cloud или свой Mimir, Loki, Tempo. CX Codex +1 6 100установок logging codewithmukesh Скилл про наблюдаемость в .NET 10: разводит liveness и readiness, прокидывает correlation ID и задаёт уровни логов. CX Codex +1 2 800установок performance-engineer sickn33 Скилл для агента: ищет узкие места по трейсам и профилям, ставит нагрузочные тесты и проверяет, что после правок стало быстрее. CX Codex +1 918установок

Рядом в теме «DevOps и инфраструктура»

Всё по теме «DevOps и инфраструктура» →

Вопросы о otel-ottl

Как установить otel-ottl в Claude Code?

Выполните команду npx skills add dash0hq/agent-skills --skill otel-ottl -a claude-code. Файл навыка сохранится в рабочий каталог агента.

Зачем нужен скилл otel-ottl?

Он помогает ассистенту без ошибок генерировать выражения на языке OTTL для OpenTelemetry Collector. Агент учитывает контексты данных, правила написания функций и особенности обработки ошибок времени выполнения.

Чем отличаются конвертеры и редакторы в синтаксисе OTTL?

Конвертеры (например, Concat, Substring, IsMatch) пишутся с заглавной буквы и возвращают вычисленное значение. Редакторы (такие как set, delete_key, limit) пишутся строчными буквами и модифицируют переданные атрибуты на месте.

Исходный текст

SKILL.md · Apache-2.0
---
name: otel-ottl
description: OpenTelemetry Transformation Language (OTTL) expert. Use when writing or debugging OTTL expressions for any OpenTelemetry Collector component that supports OTTL (processors, connectors, receivers, exporters). Triggers on tasks involving telemetry transformation, filtering, attribute manipulation, data redaction, sampling policies, routing, or Collector configuration. Covers syntax, contexts, functions, error handling, and performance.
metadata:
  author: dash0
  version: '1.0.0'
---

# OpenTelemetry Transformation Language (OTTL)

## Components that use OTTL

OTTL is not limited to the transform and filter processors.
Processors (transform, filter, tailsampling, logdedup) and connectors (routing, count, sum, signaltometrics) accept OTTL expressions.
See [components](./rules/components.md) for the full list with use cases.

## OTTL syntax

### Path expressions

Navigate telemetry data using dot notation:

```
span.name
span.attributes["http.method"]
resource.attributes["service.name"]
```

**Contexts** (first path segment): `resource`, `scope`, `span`, `spanevent`, `metric`, `datapoint`, `log`.

### Enumerations

Use int64 constants for enumeration fields:

```
span.status.code == STATUS_CODE_ERROR
span.kind == SPAN_KIND_SERVER
```

### Operators

Assignment: `=` — Comparison: `==`, `!=`, `>`, `<`, `>=`, `<=` — Logical: `and`, `or`, `not`

### Functions

**Converters** (uppercase, return values):

```
ToUpperCase(span.attributes["http.request.method"])
Substring(log.body.string, 0, 1024)
Concat(["prefix", span.attributes["request.id"]], "-")
IsMatch(metric.name, "^k8s\\..*$")
```

**Editors** (lowercase, modify data in-place):

```
set(span.attributes["region"], "us-east-1")
delete_key(resource.attributes, "internal.key")
limit(log.attributes, 10, [])
```

See [function-reference](./rules/function-reference.md) for the full list of editors and converters.

### Conditional statements

Use `where` to apply transformations conditionally:

<!-- eval:skip -->
```
span.attributes["db.statement"] = "REDACTED" where resource.attributes["service.name"] == "accounting"
```

### Nil checks

Use `nil` for absence checking (not `null`):

```
resource.attributes["service.name"] != nil
```

## Validation workflow

1. **Validate config syntax** — run `otelcol validate --config=config.yaml` to catch compilation errors before starting the Collector.
2. **Test with the debug exporter** — route transformed telemetry to a `debug` exporter and inspect the output:

```yaml
exporters:
  debug:
    verbosity: detailed

service:
  pipelines:
    traces:
      receivers: [otlp]
      processors: [transform]
      exporters: [debug]   # swap in production exporter once validated
```

3. **Set `error_mode: ignore` in production** — see [Error handling](#error-handling).
4. **Promote to production exporters** — replace `debug` with the production exporter.

## Common patterns

<!-- keep-in-sync: each entry must match a ## heading in ./rules/patterns.md -->
- [Set attributes](./rules/patterns.md#set-attributes)
- [Drop telemetry by pattern](./rules/patterns.md#drop-telemetry-by-pattern)
- [Drop stale data](./rules/patterns.md#drop-stale-data)
- [Backfill missing timestamps](./rules/patterns.md#backfill-missing-timestamps)
- [Filter processor example](./rules/patterns.md#filter-processor-example)
- [Transform processor example](./rules/patterns.md#transform-processor-example)
- [Defensive nil checks](./rules/patterns.md#defensive-nil-checks)
- [Redact sensitive data](./rules/redaction.md) — strategies: replace, mask, hash, delete, and drop.
- [Normalize high-cardinality attributes](./rules/cardinality.md) — path segments, IP masking, and attribute count/length limits.
- [Enrich telemetry with static attributes](./rules/enrichment.md)

## Error handling

### Compilation errors

Occur during processor initialization and prevent Collector startup:
- Invalid syntax (missing quotes)
- Unknown functions
- Invalid path expressions
- Type mismatches

### Runtime errors

Occur during telemetry processing:
- Accessing non-existent attributes
- Type conversion failures
- Function execution errors

### Error mode configuration

Always set `error_mode` explicitly; the default differs by component.
The transform and filter processors default to `ignore` since Collector Contrib v0.153.0 and to `propagate` before it.
The routing and signaltometrics connectors default to `propagate`.
The count and sum connectors have no `error_mode` key and always propagate errors.

| Mode | Behavior | When to use |
|------|----------|-------------|
| `ignore` | Logs the error and continues to the next statement | **Production and general use** — the default for the transform and filter processors |
| `propagate` | Returns the error up the pipeline, dropping the payload from the Collector | Development and strict environments where you want to catch every error |
| `silent` | Ignores errors without logging | High-volume pipelines with known-safe transforms where error logs are noise |

```yaml
processors:
  transform:
    error_mode: ignore
    trace_statements:
      - set(span.attributes["parsed"], ParseJSON(span.attributes["json_body"]))
```

Statements are a flat list; the Collector infers the context (`span`, `metric`, `datapoint`, `log`, and so on) from the path prefixes.
Use the object form with an explicit `context:` only when a statement group mixes paths that cannot be inferred to a single context, or when you need a group-level condition or `error_mode`.

## Performance

Use `where` clauses to skip items early.

```
# BAD — runs replace_pattern on every span
replace_pattern(span.attributes["url.path"], "/\\d+", "/{id}")

# GOOD — skips spans that lack the attribute
replace_pattern(span.attributes["url.path"], "/\\d+", "/{id}") where span.attributes["url.path"] != nil
```

## References

- [OTTL Guide](https://www.dash0.com/guides/opentelemetry-transformation-language-ottl)
- [OTTL Specification](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/pkg/ottl)
- [OTTL Functions Reference](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/pkg/ottl/ottlfuncs)
- [OTTL Playground](https://ottl.run)

© dash0 · Apache-2.0 · dash0hq/agent-skills

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой