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

otel-span-events-to-logs-migration — скилл для Claude Code

Помогает перенести события и исключения OpenTelemetry со Span Events на Logs API, сохранив связь записей с активным спаном. Пригодится для миграции и проверки старых вызовов.

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

Что делает otel-span-events-to-logs-migration

Скилл предлагает найти вызовы AddEvent, RecordException и языковые аналоги, затем классифицировать каждое место: перенести в Logs API, заменить атрибутами спана или удалить. При переносе нужно сохранить контекст спана, имя события, атрибуты и временную метку. Для исключений учитываются семантические атрибуты exception.type и exception.message; стек добавляют, когда это имеет смысл для языка и типа ошибки.

Перед работой скилл предлагает проверить поддержку событий через Logs API в версии OpenTelemetry SDK, наличие настроенного LoggerProvider и зависимость нижестоящих систем от событий в proto спана. Если такая совместимость нужна, на уровне SDK настраивается мост из логов обратно в события спана. Это важно: без LoggerProvider миграцию сначала придётся дополнить настройкой провайдера.

После изменений агент должен перечитать файлы и сверить результат с чек-листом, приложив ссылки на файлы как подтверждение. Для Go приведены указания по получению логгера и атрибутам записи; для Java — актуальный путь к мосту после удаления прежней реализации из contrib. Подробности по языковым шаблонам вынесены в файлы references.

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

  • найти вызовы Span Events в кодовой базе
  • классифицировать события для миграции, замены атрибутами или удаления
  • перенести события и исключения на Logs API с контекстом спана
  • проверить настройку LoggerProvider и обратную совместимость
  • сверить изменённые файлы с чек-листом миграции

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

  • Перенеси вызовы AddEvent и RecordException на Logs API, сохранив связь с активным спаном.
  • Найди все вызовы Span Events и классифицируй каждый для миграции, замены атрибутами или удаления.
  • Проверь миграцию OpenTelemetry по чек-листу и укажи файлы, подтверждающие каждый выполненный пункт.

Как установить otel-span-events-to-logs-migration

1Через Skills CLI (Vercel)

npx skills add ollygarden/opentelemetry-agent-skills --skill otel-span-events-to-logs-migration -a claude-code

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

~/.claude/skills/otel-span-events-to-logs-migration/SKILL.md

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

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

Вопросы о otel-span-events-to-logs-migration

Как установить otel-span-events-to-logs-migration в Claude Code?

Выполните npx skills add ollygarden/opentelemetry-agent-skills --skill otel-span-events-to-logs-migration -a claude-code. Файл скилла находится по пути ~/.claude/skills/otel-span-events-to-logs-migration/SKILL.md.

Что делает otel-span-events-to-logs-migration?

Скилл помогает перенести вызовы Span Events на Logs API, классифицировать места использования и проверить результат по чек-листу. Он также учитывает сохранение контекста спана и обратную совместимость.

Что проверить перед миграцией OpenTelemetry Span Events?

Проверьте, поддерживает ли версия SDK события через Logs API, настроен ли LoggerProvider и нужны ли нижестоящим системам события в proto спана. Если они нужны, потребуется SDK-мост из логов обратно в события.

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

SKILL.md · Apache-2.0
---
name: otel-span-events-to-logs-migration
description: Migrate OpenTelemetry Span Events (AddEvent, RecordException, and language equivalents) to the Logs API following the accepted OTEP 4430 migration plan. Use when migrating instrumentation from span events to log-based events, reviewing code that still uses AddEvent or RecordException, or planning a codebase migration while preserving trace correlation.
---

# Span Events to Logs Migration

Use this skill to migrate instrumentation from the Span Event API (`AddEvent`, `RecordException`, and language equivalents) to the Logs API, following the accepted [OTEP 4430 deprecation plan](https://github.com/open-telemetry/opentelemetry-specification/blob/v1.61.0/oteps/4430-span-event-api-deprecation-plan.md).

## Background

The OpenTelemetry project accepted a plan to deprecate `Span.AddEvent` and `Span.RecordException` in favor of emitting events and exceptions through the Logs API. Span Events as a concept remain valid -- they can be emitted via logs that correlate to the active span, and optionally bridged back into the span proto.

Status as of 2026-10-03: OTEP 4430 is accepted, log-based event/exception emission is specified in the Logs API, and the SDK "event to span event bridge" is specified with Development status. The trace API methods `AddEvent`/`RecordException` are not yet formally marked Deprecated in the specification -- that step is still pending. Treat existing span-event calls as migration candidates, not automatically invalid code; some SDK-specific equivalents have already changed status (for example OpenTelemetry .NET's `Activity.RecordException` extension is `[Obsolete]` in favor of `Activity.AddException`, which is still a span-event API).

See `references/deprecation-plan.md` for the full context.

## Workflow

0. Prepare before migrating.
- check the project's OpenTelemetry SDK version supports log-based events (check the `otel-sdk-versions` skill's version index if available)
- identify whether the project has a LoggerProvider configured; if not, one must be set up
- determine if downstream consumers (backends, dashboards, alerts) depend on span events appearing in the span proto envelope

1. Scan the codebase for span event usage.
- search for `AddEvent`, `add_event`, `addEvent`, `RecordException`, `record_exception`, `recordException`, `RecordError`, `record_error`, `AddException`, and language-specific variants
- categorize each call site: general event, exception recording, or informational annotation
- note the span context, attributes, and timestamp usage at each site

2. Classify each call site using the decision tree.
- see `references/decision-tree.md` for the full classification logic
- the three outcomes are: migrate to log-based event, convert to span attributes, or remove

3. Apply the migration for each call site.
- see `references/migration-patterns.md` for language-specific before/after patterns
- ensure the replacement log record carries the correct span context, event name, attributes, and timestamp; for exceptions use the applicable semantic-convention event name (normally an operation-specific `.exception` name), reserving `exception` for generic handlers
- in Go (1.47.0+, Logs API/SDK stable), get loggers with `otel.Logger` from the root `go.opentelemetry.io/otel` package (`otel/log/global` is deprecated)
- in Java, the contrib `io.opentelemetry.contrib.eventbridge.EventToSpanEventBridge` was removed in opentelemetry-java-contrib v1.60.0; use `io.opentelemetry.sdk.extension.incubator.logs.EventToSpanEventBridge` from `opentelemetry-sdk-extension-incubator` (see `references/backward-compat.md`)
- in Go, `log.Record.AddAttributes` accepts `attribute.KeyValue`: use `attribute.String(...)`, not `log.String(...)`; set the event name with `Record.SetEventName(...)`
- for exceptions, preserve the applicable semconv attributes: `exception.type` and `exception.message` (at least one is required), plus `exception.stacktrace` when the language/error type makes it meaningful (in Go, omit it unless an error library preserves the origin stack -- do not call `runtime.Stack` at the emit site)

4. If backward compatibility is needed, configure the SDK bridge.
- see `references/backward-compat.md`
- this is an SDK-level log processor that converts log-based events back to span events
- only needed when downstream systems require span events in the same proto envelope as the span

5. Verify the migration.

## Required Completion Loop

Follow this loop every time:
1. scan and classify all span event call sites
2. migrate each call site following the decision tree and patterns
3. review the changed code against the checklist below
4. re-open the changed files and confirm each checklist item with codebase evidence
5. if any item is unresolved, patch the code or mark it not applicable with a reason, then repeat the review
6. do not finish until every checklist item is completed or explicitly marked not applicable

Do not mark a checklist item complete based on intent alone. Mark it complete only after confirming it in the current codebase.

## Migration Checklist

For every item, report one of these statuses in the final answer:
- `[x]` completed
- `[~]` not applicable, with a reason
- `[ ]` unresolved

Include file references as evidence for every completed item.

- `[ ]` All general span-event call sites identified and classified, including `AddEvent` / `add_event` / `addEvent` and language equivalents such as .NET `ActivityEvent`.
- `[ ]` All exception span-event call sites identified and classified, including `RecordException` / `record_exception` / `recordException` and language equivalents such as Go `RecordError`, Rust `record_error`, and .NET `AddException`.
- `[ ]` A LoggerProvider is configured in the SDK setup (or already existed).
- `[ ]` Each migrated event uses the Logs API with the correct event name and attributes.
- `[ ]` Each migrated exception preserves the applicable semconv attributes: `exception.type` and `exception.message` (at least one is required), plus `exception.stacktrace` when the language/error type makes it meaningful.
- `[ ]` Migrated log records carry the active span context for trace correlation.
- `[ ]` Call sites classified as "convert to span attributes" now use span attributes instead.
- `[ ]` Call sites classified as "remove" have been removed with justification.
- `[ ]` Backward compatibility bridge is configured if downstream systems require span events in the span envelope.
- `[ ]` No remaining span-event API call sites are left unintentionally; any retained `AddEvent` / `RecordException` / `RecordError` / `AddException` / `ActivityEvent` / equivalent call is justified for current-version compatibility.
- `[ ]` The changed files were re-read after implementation to verify the final state.
- `[ ]` The final answer includes this checklist, file evidence, and any remaining risks or gaps.

## Final Review Format

In the final answer, include the checklist in this format:
- `[x]` LoggerProvider configured. Evidence: `src/telemetry/setup.go:42` -- added OTLP log exporter with batch processor.
- `[~]` Backward compatibility bridge. Reason: no downstream systems depend on span events in the proto envelope.
- `[ ]` Exception migration. Missing evidence; re-check required.

© ollygarden · Apache-2.0 · ollygarden/opentelemetry-agent-skills

Похожие скиллы

Все скиллы по теме «DevOps и инфраструктура» →
wizard Matt Pocock Скилл создаёт интерактивный bash-скрипт для ручных шагов: настройки сервисов, секретов CI и разовых миграций. 553 369установок hyperframes-cli heygen-com Управляет проектами HyperFrames через терминал: собирает таймлайн, проверяет контраст кадров, запускает предпросмотр и рендерит видео локально или в облаке. CX Codex +1 1 300 000установок setup-pre-commit Matt Pocock Скилл настраивает pre-commit для JavaScript-репозитория: Husky запускает форматирование, проверку типов и тесты перед коммитом. 489 289установок using-git-worktrees Jesse Vincent Готовит изолированное рабочее дерево перед доработкой или выполнением плана. Проверяет текущий репозиторий, выбирает нативные средства платформы либо Git. CX Codex 217 153установок finishing-a-development-branch Jesse Vincent Скилл проверяет тесты и помогает выбрать, как завершить работу в ветке: слить её, открыть Pull Request или оставить как есть. CX Codex 214 439установок orca-cli stablyai Скилл даёт агенту доступ к worktree, терминалам, артефактам и встроенному браузеру Orca через CLI. Пригодится, когда работа идёт в окружении Orca. CX Codex +1 354 000установок

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

otel-component-telemetry Сканирует один компонент OpenTelemetry на закреплённых версиях и записывает его спаны, метрики и логи в файлы изменений. CX Codex +1 ★ 116звёзд репо otel-weaver Настраивает реестры OpenTelemetry Weaver, генерацию кода и CI-проверки. Помогает описать семантические конвенции компании без ручных констант. CX Codex +1 ★ 116звёзд репо otel-upgrade Скилл оценивает обновления OpenTelemetry и предлагает путь перехода с учётом версий, совместимости и проверок в репозитории. Пригодится перед обновлением SDK, Collector или связанных компонентов. CX Codex +1 ★ 116звёзд репо otel-telemetrygen Собирает безопасные команды telemetrygen с привязкой к версии, чтобы гнать синтетические OTLP-трейсы, метрики и логи в коллектор. CX Codex +1 ★ 116звёзд репо otel-semantic-conventions Скилл подтягивает вышедшие семантические конвенции OpenTelemetry: имена групп, атрибуты и правила именования спанов. Пригодится, когда агент придумывает ключи вместо готовых. CX Codex +1 ★ 116звёзд репо otel-ruby Помогает агенту настраивать и проверять OpenTelemetry в Ruby-приложениях. Пригодится для трассировки, метрик, логов и инструментирования Rails и других библиотек. CX Codex +1 ★ 116звёзд репо otel-python Скилл для настройки и отладки OpenTelemetry в Python-сервисах: SDK, декларативный конфиг, автоинструментация без правок кода. CX Codex +1 ★ 116звёзд репо otel-ottl Скилл помогает писать выражения на OpenTelemetry Transformation Language (OTTL) для трансформирования и фильтрации телеметрии в Collector. CX Codex +1 ★ 116звёзд репо

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

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