Skip to content

Instantly share code, notes, and snippets.

@wperron
Last active April 9, 2024 16:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wperron/66205799825ab99ffb19014383e3d221 to your computer and use it in GitHub Desktop.
Save wperron/66205799825ab99ffb19014383e3d221 to your computer and use it in GitHub Desktop.
Exporting traces via OTLP/HTTP in Deno
import opentelemetry from "npm:@opentelemetry/api";
import { context, trace } from "npm:@opentelemetry/api";
import {
BasicTracerProvider,
BatchSpanProcessor,
ConsoleSpanExporter,
SimpleSpanProcessor,
} from "npm:@opentelemetry/sdk-trace-base";
import { Resource } from "npm:@opentelemetry/resources";
import { OTLPTraceExporter } from "npm:@opentelemetry/exporter-trace-otlp-proto";
import { delay } from "https://deno.land/std@0.221.0/async/mod.ts";
const exporter = new OTLPTraceExporter({
url: "http://localhost:4318/v1/traces", // url is optional and can be omitted - default is http://localhost:4318/v1/traces
concurrencyLimit: 10, // an optional limit on pending requests
});
const provider = new BasicTracerProvider({
resource: new Resource({
["service.name"]: "my-service",
}),
});
provider.addSpanProcessor(
new BatchSpanProcessor(exporter, {
// The maximum queue size. After the size is reached spans are dropped.
maxQueueSize: 1000,
// The interval between two consecutive exports
scheduledDelayMillis: 1000,
}),
);
provider.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter()));
provider.register();
const tracer = opentelemetry.trace.getTracer("example-basic-tracer-node");
// Create a span. A span must be closed.
const parentSpan = tracer.startSpan("main");
for (let i = 0; i < 10; i += 1) {
doWork(parentSpan);
}
// Be sure to end the span.
parentSpan.end();
function doWork(parent) {
// Start another span. In this example, the main method already started a
// span, so that'll be the parent span, and this will be a child span.
const ctx = trace.setSpan(context.active(), parent);
const span = tracer.startSpan("doWork", undefined, ctx);
// simulate some random work.
for (let i = 0; i <= Math.floor(Math.random() * 40000000); i += 1) {
// empty
}
// Set attributes to the span.
span.setAttribute("key", "value");
span.setAttribute("mapAndArrayValue", [
0,
1,
2.25,
"otel",
{
foo: "bar",
baz: "json",
array: [1, 2, "boom"],
},
]);
// Annotate our span to capture metadata about our operation
span.addEvent("invoking doWork");
// end span
span.end();
}
// give some time before it is closed
console.log("closing after 2s");
await delay(2000);
try {
await exporter.shutdown();
} catch (e) {
console.error(e);
}
console.log("closed");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment