Use when a task instruments or upgrades a service or worker with OpenTelemetry, or adds an endpoint, job or consumer to one that already reports - the TaskTrooper convention, recipes for Next.js on Vercel, Node.js, Go, Python, .NET, Java and Rust, and how to verify the data before and after the deploy
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Otel Instrumentation?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/makifbaysal-otel-instrumentation-tasktrooper)
---
name: otel-instrumentation
category: observability
description: Use when a task instruments or upgrades a service or worker with OpenTelemetry, or adds an endpoint, job or consumer to one that already reports - the TaskTrooper convention, recipes for Next.js on Vercel, Node.js, Go, Python, .NET, Java and Rust, and how to verify the data before and after the deploy
source: open-telemetry/opentelemetry.io docs (CC BY 4.0), adapted
---
# OpenTelemetry instrumentation
Plain OpenTelemetry, no SDK of ours. The console reads the component only when its data follows the convention below (version 1).
## Order of work
1. **Detect.** Read the manifests, the entry point and what already reports. Extend an SDK that is there; never start a second one.
2. **Package and configuration.** Follow this stack's section. Use current package versions from the registry and the repository's lockfile; do not copy a version from memory.
3. **Environment.** The endpoint and token come from environment variables, declared with `declare_env_vars` (the token as a secret). The component must start and work with them unset. A collector, an account or a data source to connect is a person's `before_deploy` step.
4. **Verify locally** with the receiver below, and paste its output into the closing comment.
5. **Pull request.** Hand off as usual. It is never merged by an agent.
6. **After the deploy**, when the card comes back with missing names, run `check_otel_conformance`: fix what is `missing` or `invalid`. `unknown` means no connected source can answer it; say so, do not change code to chase it.
## Resource attributes (every component)
| Attribute | Value |
|---|---|
| `service.name` | the component's name, the same in every release |
| `service.version` | the deployed commit's SHA, 7-40 lowercase hex digits, not the package version |
| `deployment.environment.name` | `production`, `staging`, `preview` or `development` |
| `tasktrooper.component` | the component's path in the repository, `.` for the root |
| `tasktrooper.convention.version` | `1` |
Add `vcs.ref.head.revision` (the full SHA) when the build knows it. Never put a secret, email, token, form value or query string in any attribute, and name every route by its template. A server reads them from the standard variables, set where the deploy sets environment variables:
```
OTEL_SERVICE_NAME=<component>
OTEL_RESOURCE_ATTRIBUTES=service.version=<sha>,deployment.environment.name=<env>,tasktrooper.component=<path>,tasktrooper.convention.version=1
OTEL_EXPORTER_OTLP_ENDPOINT, OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf, OTEL_EXPORTER_OTLP_HEADERS (secret)
```
`service.version` comes from what the deploy already exports (`VERCEL_GIT_COMMIT_SHA`, `GITHUB_SHA` as a build argument, `git rev-parse HEAD` in the build).
## What a service sends
A backend: `http.server.request.duration` or server spans, with `http.request.method`, `http.route` and `http.response.status_code`. A worker: a span per job; per message, a consumer span. Current names only (semantic conventions 1.23 or newer).
## Recipes
**Next.js, on Vercel or not.** Server: `npm i @vercel/otel @opentelemetry/api @opentelemetry/api-logs@latest-2 @opentelemetry/sdk-logs@latest-2 @opentelemetry/instrumentation@latest-2 @opentelemetry/sdk-trace-base@latest-2`. `@vercel/otel` accepts only the OpenTelemetry 2.x line, so take the `latest-2` tag of every `@opentelemetry/*` package in this app, `api` excepted. In `instrumentation.ts` (in `src/` when the app is there):
```ts
import { registerOTel } from "@vercel/otel";
import type { SpanProcessor } from "@opentelemetry/sdk-trace-base";
// Next.js names its own span attributes by the pre-1.23 conventions.
const currentNames: SpanProcessor = {
onStart() {},
onEnd({ attributes: a }) {
if (a["http.method"] !== undefined) a["http.request.method"] ??= a["http.method"];
if (a["http.status_code"] !== undefined) a["http.response.status_code"] ??= a["http.status_code"];
delete a["http.target"];
},
forceFlush: async () => {},
shutdown: async () => {},
};
export function register() {
const endpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT;
const sha = process.env.VERCEL_GIT_COMMIT_SHA ?? process.env.GIT_SHA;
registerOTel({
serviceName: process.env.OTEL_SERVICE_NAME ?? "<component>",
attributes: {
...(sha ? { "service.version": sha } : {}),
"deployment.environment.name": process.env.DEPLOY_ENV ?? process.env.VERCEL_ENV ?? "development",
"tasktrooper.component": "<component path>",
"tasktrooper.convention.version": "1",
},
spanProcessors: [currentNames, "auto"],
instrumentationConfig: {
fetch: { ignoreUrls: endpoint ? [endpoint] : [] },
},
});
}
```
On Vercel `VERCEL_GIT_COMMIT_SHA` and `VERCEL_ENV` are there by default ("Automatically expose system environment variables"); elsewhere the deploy sets `GIT_SHA` and `DEPLOY_ENV`. Set the `OTEL_EXPORTER_OTLP_*` variables per environment in the project's settings. Pass: a server span with `http.route` (`/orders/[id]`), `http.request.method` and `http.response.status_code`; without the name mapping Next.js sends only the old `http.method` and `http.status_code`.
**Node.js** (Express, Fastify, NestJS and others): `@opentelemetry/api` and `@opentelemetry/auto-instrumentations-node`, loaded before the app: `node --require @opentelemetry/auto-instrumentations-node/register app.js` (or the same in `NODE_OPTIONS`; `--import` for an ESM app). Pass: a `GET /orders/:id` server span and `http.server.request.duration` with `http.request.method`, `http.route`, `http.response.status_code`. A bundled server needs its libraries left external, or nothing is patched.
**Go**: build the providers in `main` and shut them down on exit. `go.opentelemetry.io/contrib/exporters/autoexport` gives `NewSpanExporter` and `NewMetricReader` that read the `OTEL_*` variables (set `OTEL_TRACES_EXPORTER` and `OTEL_METRICS_EXPORTER` to `none` where there is no endpoint). Wrap the router: `otelhttp.NewHandler(mux, "server")` over an `http.ServeMux` with method-and-pattern routes, or the router's own package (`otelgin`, `otelecho`, `otelchi`, `otelfiber`, `otelgrpc`), outbound clients with `otelhttp.NewTransport`, the database with `github.com/XSAM/otelsql`. With `otelhttp` the route is on the metric and in the span's name, not on the span: keep metrics on. Any other router under bare `otelhttp` reports no route and does not conform.
**Python**: `opentelemetry-distro` and `opentelemetry-exporter-otlp`, then `opentelemetry-bootstrap -a install` in the image build, and run under `opentelemetry-instrument` (`opentelemetry-instrument uvicorn app:app`; with a forking server, initialise in `post_fork`). Set `OTEL_SEMCONV_STABILITY_OPT_IN=http`: without it Python still sends the old `http.method` and `http.server.duration`, which do not conform.
**.NET**: `OpenTelemetry.Extensions.Hosting`, `OpenTelemetry.Instrumentation.AspNetCore`, `OpenTelemetry.Instrumentation.Http`, `OpenTelemetry.Exporter.OpenTelemetryProtocol`; then `builder.Services.AddOpenTelemetry().WithTracing(t => t.AddAspNetCoreInstrumentation().AddHttpClientInstrumentation()).WithMetrics(m => m.AddAspNetCoreInstrumentation().AddHttpClientInstrumentation()).WithLogging().UseOtlpExporter();`. Call `UseOtlpExporter` only when the endpoint is set.
**Java / Kotlin**: the `opentelemetry-javaagent.jar`, attached with `JAVA_TOOL_OPTIONS=-javaagent:/otel/opentelemetry-javaagent.jar` (2.x sends the current HTTP names; 1.x needs an upgrade). Native image: `opentelemetry-spring-boot-starter`, or Quarkus's `quarkus-opentelemetry` extension.
**Rust**: `opentelemetry`, `opentelemetry_sdk`, `opentelemetry-otlp`, `tracing-opentelemetry`; on axum `axum-tracing-opentelemetry`, whose spans carry the matched path as `http.route`.
**Workers and consumers**: the queue client's instrumentation gives consumer spans. Where there is none, start a span of kind CONSUMER per message with `messaging.destination.name` (the topic or queue), `messaging.operation.name` and `messaging.system`, and end it with the error recorded on failure.
## Local verification
A receiver that prints which names arrive; it needs only Node and reads JSON and protobuf. Keep it in the task's scratch directory, never in the repository, and stop it by its port.
```js
// otlp.mjs: node otlp.mjs
import http from "node:http"; import zlib from "node:zlib";
const want = [/service\.name/, /service\.version/, /deployment\.environment\.name/, /tasktrooper\.component/, /tasktrooper\.convention\.version/, /http\.request\.method/, /http\.route/, /http\.response\.status_code/, /messaging\.destination\.name/];
http.createServer((q, r) => { const c = []; q.on("data", (d) => c.push(d)); q.on("end", () => {
let b = Buffer.concat(c); if (q.headers["content-encoding"] === "gzip") b = zlib.gunzipSync(b);
console.log(q.url, want.map((w) => b.toString("latin1").match(w)?.[0] ?? `MISSING ${w.source}`).join(" | ")); r.end();
}); }).listen(4318, "127.0.0.1");
```
Start the component with `OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4318` and `OTEL_METRIC_EXPORT_INTERVAL=2000`, send one request (or message) that succeeds and one that fails. Passes when:
- The five resource attributes are on every request.
- A backend: a `/v1/metrics` or `/v1/traces` request carries the three `http.*` names, with the template as the route. A worker: a `/v1/traces` request carries a span for the job, with `messaging.destination.name` for a message.
- With the endpoint unset the component still starts and works, and nothing but a log line changes.
A missing name on a request of another kind is normal (a metrics post carries no span attribute). "It compiles" and "the SDK is installed" prove nothing.
## Upgrading from an older version
A card that says upgrade carries both versions. Read what the new version asks (the card's missing and wrong names, and `check_otel_conformance`), change only those names, keep the old name beside the new one for one release when a dashboard reads it, and raise `tasktrooper.convention.version` in the same pull request, last: the data is judged by the version it declares.
## New code in an instrumented component
A new route needs nothing when the router is wrapped: check it appears under its template. A new job, consumer or scheduled task gets a span of its own; a new outbound client gets its instrumentation. Name spans after the operation, never after an id.
## Traps
- Another SDK (Datadog, Sentry tracing, New Relic) already patches the libraries: keep one tracer, or point the existing one at OTLP.
- Metrics in a short-lived or serverless function need a flush before it returns.
- Health checks fill the traces: exclude their route in the instrumentation, never by dropping the server span of real routes.
- Busy production service: `OTEL_TRACES_SAMPLER=parentbased_traceidratio` with `0.1`; metrics are not sampled.