Skip to content

Commit

Permalink
add sentry span code
Browse files Browse the repository at this point in the history
  • Loading branch information
AbhiPrasad authored and mydea committed Oct 28, 2022
1 parent acfc296 commit 8da91c5
Showing 1 changed file with 64 additions and 4 deletions.
68 changes: 64 additions & 4 deletions packages/opentelemetry-node/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,84 @@
import { Context } from '@opentelemetry/api';
import { Span as OtelSpan, SpanProcessor as OtelSpanProcessor } from '@opentelemetry/sdk-trace-base';
import { getCurrentHub } from '@sentry/core';
import { Span as SentrySpan } from '@sentry/types';

/**
* Converts OpenTelemetry Spans to Sentry Spans and sends them to Sentry via
* the Sentry SDK.
*/
export class SentrySpanProcessor implements OtelSpanProcessor {
private readonly _map: Record<SentrySpan['spanId'], [SentrySpan, SentrySpan | undefined]> = {};

/**
* @inheritDoc
*/
public onStart(span: OtelSpan, parentContext: Context): void {
// do something
public onStart(otelSpan: OtelSpan, _parentContext: Context): void {
const hub = getCurrentHub();
if (!hub) {
return;
}
const scope = hub.getScope();
if (!scope) {
return;
}

// if isSentryRequest(otelSpan) return;

const otelSpanId = otelSpan.spanContext().spanId;

const sentryParentSpan = scope.getSpan();
if (sentryParentSpan) {
const sentryChildSpan = sentryParentSpan.startChild({
description: otelSpan.name,
// instrumentor: 'otel',
startTimestamp: otelSpan.startTime[0],
});
sentryChildSpan.spanId = otelSpanId;

this._map[otelSpanId] = [sentryChildSpan, sentryParentSpan];
scope.setSpan(sentryChildSpan);
} else {
// const traceCtx = getTraceData(otelSpan);
const transaction = hub.startTransaction({
name: otelSpan.name,
// ...traceCtx,
// instrumentor: 'otel',
startTimestamp: otelSpan.startTime[0],
});
transaction.spanId = otelSpanId;

this._map[otelSpanId] = [transaction, undefined];
scope.setSpan(transaction);
}
}

/**
* @inheritDoc
*/
public onEnd(span: OtelSpan): void {
// do something
public onEnd(otelSpan: OtelSpan): void {
const hub = getCurrentHub();
if (!hub) {
return;
}
const scope = hub.getScope();
if (!scope) {
return;
}

const otelSpanId = otelSpan.spanContext().spanId;
const mapVal = this._map[otelSpanId];

if (mapVal) {
const [sentrySpan, sentryParentSpan] = mapVal;

// updateSpanWithOtelData(sentrySpan, otelSpan);

sentrySpan.finish(otelSpan.endTime[0]);
scope.setSpan(sentryParentSpan);
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete this._map[otelSpanId];
}
}

/**
Expand Down

0 comments on commit 8da91c5

Please sign in to comment.