Skip to content
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ For notes on migrating to 2.x / 0.200.x see [the upgrade guide](doc/upgrade-to-2

### :rocket: Features

* feat(sdk-trace): implement span start/end metrics [#1851](https://github.com/open-telemetry/opentelemetry-js/pull/6213) @anuraaga

### :bug: Bug Fixes

* fix(opentelemetry-sdk-node): the custom value from env variable for service.instance.id should take priority over random uuid as backup [#6345](https://github.com/open-telemetry/opentelemetry-js/pull/6345) @maryliag
Expand Down
11 changes: 8 additions & 3 deletions e2e-tests/verify.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,14 @@ for (const line of lines) {
verifiedSpan = true;
}
if (parsed.resourceMetrics) {
console.log('found metric');
verifyMetric(parsed.resourceMetrics[0].scopeMetrics[0].metrics[0]);
verifiedMetric = true;
const scopeMetrics = parsed.resourceMetrics[0].scopeMetrics.find(
sm => sm.scope.name === 'example-meter'
);
if (scopeMetrics) {
console.log('found metric');
verifyMetric(scopeMetrics.metrics[0]);
verifiedMetric = true;
}
}
if (parsed.resourceLogs) {
console.log('found log');
Expand Down
45 changes: 23 additions & 22 deletions experimental/packages/opentelemetry-sdk-node/src/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,28 @@ export class NodeSDK {
})
);

if (
this._meterProviderConfig?.readers &&
// only register if there is a reader, otherwise we waste compute/memory.
this._meterProviderConfig.readers.length > 0
) {
const meterProvider = new MeterProvider({
resource: this._resource,
views: this._meterProviderConfig?.views ?? [],
readers: this._meterProviderConfig.readers,
});

this._meterProvider = meterProvider;
metrics.setGlobalMeterProvider(meterProvider);

// TODO: This is a workaround to fix https://github.com/open-telemetry/opentelemetry-js/issues/3609
// If the MeterProvider is not yet registered when instrumentations are registered, all metrics are dropped.
// This code is obsolete once https://github.com/open-telemetry/opentelemetry-js/issues/3622 is implemented.
for (const instrumentation of this._instrumentations) {
instrumentation.setMeterProvider(metrics.getMeterProvider());
}
}

const spanProcessors = this._tracerProviderConfig
? this._tracerProviderConfig.spanProcessors
: getSpanProcessorsFromEnv();
Expand All @@ -335,6 +357,7 @@ export class NodeSDK {
this._tracerProvider = new NodeTracerProvider({
...this._configuration,
resource: this._resource,
meterProvider: this._meterProvider,
spanProcessors,
});
trace.setGlobalTracerProvider(this._tracerProvider);
Expand All @@ -351,28 +374,6 @@ export class NodeSDK {

logs.setGlobalLoggerProvider(loggerProvider);
}

if (
this._meterProviderConfig?.readers &&
// only register if there is a reader, otherwise we waste compute/memory.
this._meterProviderConfig.readers.length > 0
) {
const meterProvider = new MeterProvider({
resource: this._resource,
views: this._meterProviderConfig?.views ?? [],
readers: this._meterProviderConfig.readers,
});

this._meterProvider = meterProvider;
metrics.setGlobalMeterProvider(meterProvider);

// TODO: This is a workaround to fix https://github.com/open-telemetry/opentelemetry-js/issues/3609
// If the MeterProvider is not yet registered when instrumentations are registered, all metrics are dropped.
// This code is obsolete once https://github.com/open-telemetry/opentelemetry-js/issues/3622 is implemented.
for (const instrumentation of this._instrumentations) {
instrumentation.setMeterProvider(metrics.getMeterProvider());
}
}
}

public shutdown(): Promise<void> {
Expand Down
31 changes: 31 additions & 0 deletions experimental/packages/opentelemetry-sdk-node/test/sdk.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,37 @@ describe('Node SDK', () => {
await sdk.shutdown();
});

it('should register a meter provider to the tracer provider if both initialized', async () => {
const exporter = new ConsoleMetricExporter();
const metricReader = new PeriodicExportingMetricReader({
exporter: exporter,
exportIntervalMillis: 100,
exportTimeoutMillis: 100,
});

const sdk = new NodeSDK({
metricReader: metricReader,
traceExporter: new ConsoleSpanExporter(),
autoDetectResources: false,
});

sdk.start();

assertDefaultContextManagerRegistered();
assertDefaultPropagatorRegistered();

assert.strictEqual(setGlobalTracerProviderSpy.callCount, 1);
const tracerProvider = setGlobalTracerProviderSpy.lastCall.args[0];
assert.ok(tracerProvider instanceof NodeTracerProvider);
assert.ok(
(tracerProvider as any)._config.meterProvider instanceof MeterProvider

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know this isn't great but couldn't think of anything better. Let me know if you have any ideas

);

assert.ok(metrics.getMeterProvider() instanceof MeterProvider);

await sdk.shutdown();
});

it('should register a logger provider if a log record processor is provided', async () => {
process.env.OTEL_TRACES_EXPORTER = 'none';
const logRecordExporter = new InMemoryLogRecordExporter();
Expand Down
51 changes: 51 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions packages/opentelemetry-sdk-trace-base/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@
},
"devDependencies": {
"@opentelemetry/api": ">=1.3.0 <1.10.0",
"@opentelemetry/sdk-metrics": "2.2.0",
"@types/benchmark": "2.1.5",
"@types/mocha": "10.0.10",
"@types/node": "18.19.130",
Expand Down
4 changes: 4 additions & 0 deletions packages/opentelemetry-sdk-trace-base/src/Span.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ interface SpanOptions {
attributes?: Attributes;
spanLimits: SpanLimits;
spanProcessor: SpanProcessor;
recordEndMetrics?: () => void;
}

/**
Expand Down Expand Up @@ -105,6 +106,7 @@ export class SpanImpl implements Span {
private readonly _spanProcessor: SpanProcessor;
private readonly _spanLimits: SpanLimits;
private readonly _attributeValueLengthLimit: number;
private readonly _recordEndMetrics?: () => void;

private readonly _performanceStartTime: number;
private readonly _performanceOffset: number;
Expand Down Expand Up @@ -133,6 +135,7 @@ export class SpanImpl implements Span {
this.startTime = this._getTime(opts.startTime ?? now);
this.resource = opts.resource;
this.instrumentationScope = opts.scope;
this._recordEndMetrics = opts.recordEndMetrics;

if (opts.attributes != null) {
this.setAttributes(opts.attributes);
Expand Down Expand Up @@ -300,6 +303,7 @@ export class SpanImpl implements Span {
this._spanProcessor.onEnding(this);
}

this._recordEndMetrics?.();
this._ended = true;
this._spanProcessor.onEnd(this);
}
Expand Down
13 changes: 13 additions & 0 deletions packages/opentelemetry-sdk-trace-base/src/Tracer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import { Sampler } from './Sampler';
import { IdGenerator } from './IdGenerator';
import { RandomIdGenerator } from './platform';
import { Resource } from '@opentelemetry/resources';
import { TracerMetrics } from './TracerMetrics';

/**
* This class represents a basic tracer.
Expand All @@ -41,6 +42,7 @@ export class Tracer implements api.Tracer {

private readonly _resource: Resource;
private readonly _spanProcessor: SpanProcessor;
private readonly _tracerMetrics: TracerMetrics;

/**
* Constructs a new Tracer instance.
Expand All @@ -59,6 +61,11 @@ export class Tracer implements api.Tracer {
this._resource = resource;
this._spanProcessor = spanProcessor;
this.instrumentationScope = instrumentationScope;

const meter = localConfig.meterProvider
? localConfig.meterProvider.getMeter('@opentelemetry/sdk-trace')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps this change to add a version to that Meter's instrumentationScope:

diff --git a/packages/opentelemetry-sdk-trace-base/src/Tracer.ts b/packages/opentelemetry-sdk-trace-base/src/Tracer.ts
index 2694f872f..eb84fd205 100644
--- a/packages/opentelemetry-sdk-trace-base/src/Tracer.ts
+++ b/packages/opentelemetry-sdk-trace-base/src/Tracer.ts
@@ -29,6 +29,7 @@ import { IdGenerator } from './IdGenerator';
 import { RandomIdGenerator } from './platform';
 import { Resource } from '@opentelemetry/resources';
 import { TracerMetrics } from './TracerMetrics';
+import { VERSION } from './version';

 /**
  * This class represents a basic tracer.
@@ -63,7 +64,7 @@ export class Tracer implements api.Tracer {
     this.instrumentationScope = instrumentationScope;

     const meter = localConfig.meterProvider
-      ? localConfig.meterProvider.getMeter('@opentelemetry/sdk-trace')
+      ? localConfig.meterProvider.getMeter('@opentelemetry/sdk-trace', VERSION)
       : api.createNoopMeter();
     this._tracerMetrics = new TracerMetrics(meter);
   }

Instrumentations typically pass in their package version to be used for instrumentationScope.version for their tracer/meter/logger.

: api.createNoopMeter();
this._tracerMetrics = new TracerMetrics(meter);
}

/**
Expand Down Expand Up @@ -120,6 +127,11 @@ export class Tracer implements api.Tracer {
links
);

const recordEndMetrics = this._tracerMetrics.startSpan(
parentSpanContext,
samplingResult.decision
);

traceState = samplingResult.traceState ?? traceState;

const traceFlags =
Expand Down Expand Up @@ -154,6 +166,7 @@ export class Tracer implements api.Tracer {
startTime: options.startTime,
spanProcessor: this._spanProcessor,
spanLimits: this._spanLimits,
recordEndMetrics,
});
return span;
}
Expand Down
88 changes: 88 additions & 0 deletions packages/opentelemetry-sdk-trace-base/src/TracerMetrics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Counter, Meter, SpanContext, UpDownCounter } from '@opentelemetry/api';
import { SamplingDecision } from './Sampler';
import {
ATTR_OTEL_SPAN_PARENT_ORIGIN,
ATTR_OTEL_SPAN_SAMPLING_RESULT,
METRIC_OTEL_SDK_SPAN_LIVE,
METRIC_OTEL_SDK_SPAN_STARTED,
} from './semconv';

/**
* Generates `otel.sdk.span.*` metrics.
* https://opentelemetry.io/docs/specs/semconv/otel/sdk-metrics/#span-metrics
*/
export class TracerMetrics {
Comment thread
anuraaga marked this conversation as resolved.
private readonly startedSpans: Counter;
private readonly liveSpans: UpDownCounter;

constructor(meter: Meter) {
this.startedSpans = meter.createCounter(METRIC_OTEL_SDK_SPAN_STARTED, {
unit: '{span}',
description: 'The number of created spans.',
});

this.liveSpans = meter.createUpDownCounter(METRIC_OTEL_SDK_SPAN_LIVE, {
unit: '{span}',
description: 'The number of currently live spans.',
});
}

startSpan(
parentSpanCtx: SpanContext | undefined,
samplingDecision: SamplingDecision
): () => void {
const samplingDecisionStr = samplingDecisionToString(samplingDecision);
this.startedSpans.add(1, {
[ATTR_OTEL_SPAN_PARENT_ORIGIN]: parentOrigin(parentSpanCtx),
[ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr,
});

if (samplingDecision === SamplingDecision.NOT_RECORD) {
return () => {};
}

const liveSpanAttributes = {
[ATTR_OTEL_SPAN_SAMPLING_RESULT]: samplingDecisionStr,
};
this.liveSpans.add(1, liveSpanAttributes);
return () => {
this.liveSpans.add(-1, liveSpanAttributes);
};
}
}

function parentOrigin(parentSpanContext: SpanContext | undefined): string {
if (!parentSpanContext) {
return 'none';
}
if (parentSpanContext.isRemote) {
return 'remote';
}
return 'local';
}

function samplingDecisionToString(decision: SamplingDecision): string {
switch (decision) {
case SamplingDecision.RECORD_AND_SAMPLED:
return 'RECORD_AND_SAMPLE';
Comment thread
trentm marked this conversation as resolved.
case SamplingDecision.RECORD:
return 'RECORD_ONLY';
case SamplingDecision.NOT_RECORD:
return 'DROP';
}
}
Loading
Loading