Skip to content

Instantly share code, notes, and snippets.

@adamhjk
Last active May 20, 2020 19:17
Show Gist options
  • Save adamhjk/1e0f002cd95d303768de413df6a603cd to your computer and use it in GitHub Desktop.
Save adamhjk/1e0f002cd95d303768de413df6a603cd to your computer and use it in GitHub Desktop.
Opentelemetry manual trace propagation
import { WebTracerProvider } from "@opentelemetry/web";
import { ZoneContextManager } from "@opentelemetry/context-zone";
import { CollectorExporter } from "@opentelemetry/exporter-collector";
import * as api from "@opentelemetry/api";
const provider = new WebTracerProvider({
//plugins: [new DocumentLoad() as any, new UserInteractionPlugin()],
plugins: [new DocumentLoad() as any],
});
provider.addSpanProcessor(
new SimpleSpanProcessor(
new CollectorExporter({
serviceName: "si-web-app",
}),
),
);
provider.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter()));
provider.register({
contextManager: new ZoneContextManager(),
});
const tracer = provider.getTracer("yourapp");
parentSpan = tracer.startSpan("I am the parent");
const span = tracer.withSpan(parentSpan, _ => {
const span = tracer.startSpan(
name,
options,
context || api.context.active(),
);
return span;
});
// Later, you want to generate a header for trace propagation
const headers = tracer.withSpan(span, () => {
const headers: Record<string, unknown> = {};
api.propagation.inject(headers, (headers, k, v) => {
headers[k] = v;
});
return headers;
});
console.log("headers have the right traceparent", headers);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment