Skip to content

Commit 220798c

Browse files
committed
add sentry span code
1 parent e0c621a commit 220798c

File tree

1 file changed

+64
-4
lines changed

1 file changed

+64
-4
lines changed

packages/opentelemetry-node/src/index.ts

Lines changed: 64 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,84 @@
11
import { Context } from '@opentelemetry/api';
22
import { Span as OtelSpan, SpanProcessor as OtelSpanProcessor } from '@opentelemetry/sdk-trace-base';
33
import { getCurrentHub } from '@sentry/core';
4+
import { Span as SentrySpan } from '@sentry/types';
45

56
/**
67
* Converts OpenTelemetry Spans to Sentry Spans and sends them to Sentry via
78
* the Sentry SDK.
89
*/
910
export class SentrySpanProcessor implements OtelSpanProcessor {
11+
private readonly _map: Record<SentrySpan['spanId'], [SentrySpan, SentrySpan | undefined]> = {};
12+
1013
/**
1114
* @inheritDoc
1215
*/
13-
public onStart(span: OtelSpan, parentContext: Context): void {
14-
// do something
16+
public onStart(otelSpan: OtelSpan, _parentContext: Context): void {
17+
const hub = getCurrentHub();
18+
if (!hub) {
19+
return;
20+
}
21+
const scope = hub.getScope();
22+
if (!scope) {
23+
return;
24+
}
25+
26+
// if isSentryRequest(otelSpan) return;
27+
28+
const otelSpanId = otelSpan.spanContext().spanId;
29+
30+
const sentryParentSpan = scope.getSpan();
31+
if (sentryParentSpan) {
32+
const sentryChildSpan = sentryParentSpan.startChild({
33+
description: otelSpan.name,
34+
// instrumentor: 'otel',
35+
startTimestamp: otelSpan.startTime[0],
36+
});
37+
sentryChildSpan.spanId = otelSpanId;
38+
39+
this._map[otelSpanId] = [sentryChildSpan, sentryParentSpan];
40+
scope.setSpan(sentryChildSpan);
41+
} else {
42+
// const traceCtx = getTraceData(otelSpan);
43+
const transaction = hub.startTransaction({
44+
name: otelSpan.name,
45+
// ...traceCtx,
46+
// instrumentor: 'otel',
47+
startTimestamp: otelSpan.startTime[0],
48+
});
49+
transaction.spanId = otelSpanId;
50+
51+
this._map[otelSpanId] = [transaction, undefined];
52+
scope.setSpan(transaction);
53+
}
1554
}
1655

1756
/**
1857
* @inheritDoc
1958
*/
20-
public onEnd(span: OtelSpan): void {
21-
// do something
59+
public onEnd(otelSpan: OtelSpan): void {
60+
const hub = getCurrentHub();
61+
if (!hub) {
62+
return;
63+
}
64+
const scope = hub.getScope();
65+
if (!scope) {
66+
return;
67+
}
68+
69+
const otelSpanId = otelSpan.spanContext().spanId;
70+
const mapVal = this._map[otelSpanId];
71+
72+
if (mapVal) {
73+
const [sentrySpan, sentryParentSpan] = mapVal;
74+
75+
// updateSpanWithOtelData(sentrySpan, otelSpan);
76+
77+
sentrySpan.finish(otelSpan.endTime[0]);
78+
scope.setSpan(sentryParentSpan);
79+
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
80+
delete this._map[otelSpanId];
81+
}
2282
}
2383

2484
/**

0 commit comments

Comments
 (0)