Skip to content

Commit

Permalink
fix: use http instrumentation for ignoring health check trace (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
dohaki authored Jun 11, 2024
1 parent 7e672ca commit d8c4ce4
Showing 1 changed file with 13 additions and 40 deletions.
53 changes: 13 additions & 40 deletions src/lib/tracing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,54 +2,27 @@ import { registerInstrumentations } from "@opentelemetry/instrumentation";
import { HttpInstrumentation } from "@opentelemetry/instrumentation-http";
import { ExpressInstrumentation } from "@opentelemetry/instrumentation-express";
import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
import {
BatchSpanProcessor,
AlwaysOnSampler,
Sampler,
SamplingDecision,
} from "@opentelemetry/sdk-trace-base";
import { BatchSpanProcessor } from "@opentelemetry/sdk-trace-base";
import { TraceExporter } from "@google-cloud/opentelemetry-cloud-trace-exporter";
import { SpanKind, Attributes } from "@opentelemetry/api";
import { SEMATTRS_HTTP_ROUTE } from "@opentelemetry/semantic-conventions";

export function initTracing() {
const provider = new NodeTracerProvider({
sampler: filterSampler(ignoreHealthCheck, new AlwaysOnSampler()),
});
const provider = new NodeTracerProvider();
const exporter = new TraceExporter();

provider.register();
provider.addSpanProcessor(new BatchSpanProcessor(exporter));

registerInstrumentations({
instrumentations: [new ExpressInstrumentation(), new HttpInstrumentation()],
instrumentations: [
new HttpInstrumentation({
ignoreIncomingRequestHook(req) {
if (req.url.match("/health")) {
return true;
}
return false;
},
}),
new ExpressInstrumentation(),
],
});
}

function filterSampler(
filterFn: (spanName: string, spanKind: SpanKind, attr: Attributes) => boolean,
parent: Sampler,
): Sampler {
return {
shouldSample(ctx, tid, spanName, spanKind, attr, links) {
if (!filterFn(spanName, spanKind, attr)) {
return { decision: SamplingDecision.NOT_RECORD };
}
return parent.shouldSample(ctx, tid, spanName, spanKind, attr, links);
},
toString() {
return `FilterSampler(${parent.toString()})`;
},
};
}

function ignoreHealthCheck(
spanName: string,
spanKind: SpanKind,
attributes: Attributes,
) {
return (
spanKind !== SpanKind.SERVER ||
attributes[SEMATTRS_HTTP_ROUTE] !== "/health"
);
}

0 comments on commit d8c4ce4

Please sign in to comment.