js/opentelemetry/traces

js/opentelemetry/traces.ts

fino:opentelemetry/traces - trace providers, tracers, spans, and trace records.

This module contains the public trace signal API. Use it to create manual spans, swap tracer providers for tests or scoped execution, inspect the active span, and describe trace records consumed by SDK processors and exporters.

Span names and tracer scope names must be non-empty strings. Span attributes, events, links, status updates, and rename operations are published as runtime telemetry records; processors may apply additional SDK limits before export. Active-span context follows Fino async context propagation and is visible through getActiveSpan() and getActiveSpanContext().

import { getTracerProvider, runWithActiveSpan } from 'fino:opentelemetry/traces';

const tracer = getTracerProvider().getTracer('orders', '1.0.0');
const span = tracer.startSpan('orders.create', { attributes: { tenant: 'acme' } });
runWithActiveSpan(span, () => {
  span.addEvent('validated');
});
span.end({ status: { code: 'OK' } });

See OpenTelemetry traces: https://opentelemetry.io/docs/concepts/signals/traces/

Classes

class AlwaysOnSampler extends Sampler {

Sampler that keeps every span — the explicit "always on" policy.

Behaviorally identical to the base Sampler, but named so an SDK configuration can state its intent. This is the default sampler the SDK installs when none is supplied.

import { AlwaysOnSampler } from 'internal:opentelemetry/traces';

const sampler = new AlwaysOnSampler();
sampler.shouldSample({
  traceId: '00000000000000000000000000000001',
  spanId: '0000000000000001',
}); // true

class Sampler {

Consumer-side sampling hook: decides whether a completed span record should be exported.

This is the base class and default policy — its shouldSample returns true, so every span is kept. Unlike head-based OpenTelemetry samplers, sampling here runs after the span record has been assembled and limited (see the SDK's processor pipeline), which lets a sampler inspect the final attributes, status, and events before deciding. Subclass and override shouldSample to drop or enrich records.

import { Sampler } from 'internal:opentelemetry/traces';
import type { SpanRecord, SamplingResult } from 'internal:opentelemetry/common';

class ErrorsOnlySampler extends Sampler {
  shouldSample(record: SpanRecord): SamplingResult | boolean {
    return record.status?.code === 'ERROR';
  }
}

Methods

shouldSample(_record: SpanRecord): SamplingResult | boolean

Returns whether the given span record should be sampled, or a SamplingResult with overrides.

The base implementation always returns true. A boolean return keeps (true) or drops (false) the record as-is; returning a SamplingResult lets a sampler additionally merge attributes or set traceState on the exported record. The record passed in has already had span limits applied.

import { Sampler } from 'internal:opentelemetry/traces';

const keep = new Sampler().shouldSample({
  traceId: '00000000000000000000000000000001',
  spanId: '0000000000000001',
});

class Span {

A single in-progress or completed operation, emitting its lifecycle as topic records.

Constructing a span (usually via Tracer.startSpan) immediately publishes a start record; end() publishes an end record. Between those, mutation methods (setAttribute, addEvent, addLink, setStatus, recordException, updateName) each publish their own scoped topic record rather than buffering state on the instance, so processors assemble the final span from the record stream. This makes a Span a thin publisher, not the system of record.

On construction the span inherits traceId and parentSpanId from the active span context (see runWithActiveSpan) unless overridden through SpanStartOptions. A fresh random spanId is always generated. Span names must be non-empty. end() is idempotent — subsequent calls are ignored and isRecording() returns false.

import { getTracerProvider } from 'internal:opentelemetry/traces';

const tracer = getTracerProvider().getTracer('checkout');
const span = tracer.startSpan('checkout.submit', { kind: 'server' });
try {
  span.setAttribute('cart.size', 3);
} catch (err) {
  span.recordException(err);
} finally {
  span.end();
}

Constructors

constructor(tracer: Tracer, name: string, options: SpanStartOptions = {})

Creates a span, derives its identity from the active context, and publishes the start record.

The trace ID resolves in order of options.traceId, the active span context's trace ID, then a new random ID; the parent span ID resolves from options.parentSpanId (honoring an explicit null) or the active span. options.attributes seed the start record, and each entry in options.links is emitted as a link record. Throws if name is empty.

import { Span, getTracerProvider } from 'internal:opentelemetry/traces';

const tracer = getTracerProvider().getTracer('db');
const span = new Span(tracer, 'SELECT users', {
  kind: 'client',
  attributes: { 'db.system': 'postgresql' },
});

Getters

get traceId(): string

The span's lowercase-hex trace ID, shared by every span in the same trace.

import { getTracerProvider } from 'internal:opentelemetry/traces';

const span = getTracerProvider().getTracer('x').startSpan('op');
const traceId = span.traceId;
get spanId(): string

The span's lowercase-hex span ID, unique to this span within its trace.

import { getTracerProvider } from 'internal:opentelemetry/traces';

const span = getTracerProvider().getTracer('x').startSpan('op');
const spanId = span.spanId;

Methods

setAttribute(key: string, value: unknown): this

Sets a single attribute on the span by publishing an attribute mutation record.

Returns this for chaining. The value is not validated or truncated here — span limits are applied later by applySpanLimits during export. A later write to the same key wins because processors replay records in order.

import { getTracerProvider } from 'internal:opentelemetry/traces';

const span = getTracerProvider().getTracer('http').startSpan('GET /orders');
span.setAttribute('http.response.status_code', 200);
setAttributes(attributes: Attributes): this

Sets several attributes at once, publishing one attribute record per entry.

Equivalent to calling setAttribute for each own enumerable entry of attributes; a nullish argument is treated as empty. Returns this.

import { getTracerProvider } from 'internal:opentelemetry/traces';

const span = getTracerProvider().getTracer('http').startSpan('GET /orders');
span.setAttributes({ 'http.request.method': 'GET', 'url.path': '/orders' });
addEvent(name: string, attributes: Attributes = {}, timeUnixNano: number = nowUnixNano()): this

Records a timestamped, named event on the span.

timeUnixNano defaults to now; pass an explicit value to backdate an event. The attributes are shallow-copied into the record. Returns this.

import { getTracerProvider } from 'internal:opentelemetry/traces';

const span = getTracerProvider().getTracer('cache').startSpan('lookup');
span.addEvent('cache.miss', { 'cache.key': 'user:42' });
setStatus(status: SpanStatus | null): this

Sets (or clears) the span's terminal status.

Passing a SpanStatus publishes a copy of it; passing null publishes a cleared status, which processors treat as unset. Returns this.

import { getTracerProvider } from 'internal:opentelemetry/traces';

const span = getTracerProvider().getTracer('rpc').startSpan('call');
span.setStatus({ code: 'ERROR', message: 'deadline exceeded' });
recordException(error: unknown, attributes: Attributes = {}): this

Records an exception on the span: sets an error status and adds an exception event.

Non-Error values are coerced to an Error via String(error). The status is set to ERROR with the error message, and an event named exception is added with exception.type, exception.message, and (when present) exception.stacktrace attributes, merged with any extra attributes you supply. Returns this.

import { getTracerProvider } from 'internal:opentelemetry/traces';

const span = getTracerProvider().getTracer('db').startSpan('query');
try {
  throw new Error('connection reset');
} catch (err) {
  span.recordException(err, { retryable: true });
}
updateName(name: string): this

Renames the span, publishing a rename record and updating the local name.

The new name feeds subsequent records' operation field. Throws if name is empty. Returns this.

import { getTracerProvider } from 'internal:opentelemetry/traces';

const span = getTracerProvider().getTracer('http').startSpan('request');
span.updateName('GET /orders/:id');
isRecording(): boolean

Returns whether the span is still open (has not been ended).

Once end() runs this returns false, signalling that further mutations, while still published, are logically post-completion.

import { getTracerProvider } from 'internal:opentelemetry/traces';

const span = getTracerProvider().getTracer('x').startSpan('op');
span.isRecording(); // true
span.end();
span.isRecording(); // false
end(options: SpanEndOptions = {}): void

Finalizes the span and publishes its end record; idempotent after the first call.

Calling end() again after the span has ended is a no-op. Any options.attributes and options.status are published first, stamped with the end timestamp so they do not appear to post-date the span's completion, then the end record carries both the end time and the original start time.

import { getTracerProvider } from 'internal:opentelemetry/traces';

const span = getTracerProvider().getTracer('job').startSpan('run');
span.end({ status: { code: 'OK' }, attributes: { 'job.records': 128 } });

class Tracer {

Scope-bound span factory that publishes span lifecycle records onto trace topics.

A Tracer is created by TracerProvider.getTracer and carries a fixed instrumentation ScopeInfo. It precomputes the topic set for each span phase (start, end, event, attribute, link, status, rename) — one topic for the base scope name plus, when the scope has a version, a versioned topic — so publishTrace fans a record out to every matching processor. Instrumentation and application code normally use startSpan and let Span drive publishing.

import { getTracerProvider } from 'internal:opentelemetry/traces';

const tracer = getTracerProvider().getTracer('orders', '1.0.0');
const span = tracer.startSpan('orders.create', { kind: 'server' });
span.end();

Constructors

constructor(provider: TracerProvider, scope: ScopeInfo)

Binds the tracer to a provider and scope and precomputes its per-phase topics.

Constructed indirectly through TracerProvider.getTracer; direct construction requires an already-normalized ScopeInfo.

import { Tracer, TracerProvider } from 'internal:opentelemetry/traces';
import { normalizeScope } from 'internal:opentelemetry/common';

const tracer = new Tracer(new TracerProvider(), normalizeScope('db', '1.0.0'));

Getters

get scope(): ScopeInfo

A defensive copy of this tracer's instrumentation scope.

Returns a fresh object each call, so mutating the result cannot alter the tracer's internal scope.

import { getTracerProvider } from 'internal:opentelemetry/traces';

const scope = getTracerProvider().getTracer('db', '1.0.0').scope;
scope.name; // 'db'

Methods

publishTrace( kind: 'start' | 'end' | 'event' | 'attribute' | 'link' | 'status' | 'rename', payload: SpanRecord & Record<string, unknown> ): void

Publishes one span-phase record, enriched with this tracer's scope and resource.

The record is shallow-copied and stamped with a copy of the scope and the provider's resource, then published to every topic registered for the given phase. Called by Span for each lifecycle event; rarely invoked directly.

import { getTracerProvider } from 'internal:opentelemetry/traces';

const tracer = getTracerProvider().getTracer('db', '1.0.0');
tracer.publishTrace('event', {
  traceId: '00000000000000000000000000000001',
  spanId: '0000000000000001',
  event: { name: 'cache.hit' },
});
startSpan(name: string, options: SpanStartOptions = {}): Span

Starts a new span in this tracer's scope, publishing its start record immediately.

A convenience wrapper over new Span(this, name, options). Throws if name is empty. The returned span inherits trace and parent IDs from the active span context unless options overrides them.

import { getTracerProvider } from 'internal:opentelemetry/traces';

const tracer = getTracerProvider().getTracer('http.server');
const span = tracer.startSpan('GET /orders', { kind: 'server' });
span.end();

class TracerProvider extends BaseProvider {

Factory for Tracer instances, scoped to a resource.

Extends BaseProvider, so it carries the resource describing the emitting service (defaulting to Fino SDK attributes when constructed without one). Each getTracer call mints a Tracer bound to a named instrumentation scope; that scope drives which topics span records are published on. There is a process-wide default provider plus a context-scoped override — see getTracerProvider and runWithTracerProvider.

import { TracerProvider } from 'internal:opentelemetry/traces';
import { Resource } from 'internal:opentelemetry/common';

const provider = new TracerProvider({
  resource: new Resource({ 'service.name': 'orders' }),
});
const tracer = provider.getTracer('orders.db', '1.0.0');

Methods

getTracer(name: string, version?: string, options?: { schemaUrl?: string | null; attributes?: Attributes; droppedAttributesCount?: number; }): Tracer

Returns a Tracer bound to the named instrumentation scope and this provider's resource.

name must be a non-empty string identifying the instrumenting library or subsystem; it throws otherwise. version and options.schemaUrl, options.attributes, and options.droppedAttributesCount further qualify the scope and flow through to every emitted record. The scope is normalized via normalizeScope, so passing an empty name fails fast.

import { TracerProvider } from 'internal:opentelemetry/traces';

const tracer = new TracerProvider().getTracer('http.server', '2.0.0', {
  schemaUrl: 'https://opentelemetry.io/schemas/1.27.0',
});

Functions

function applySpanLimits(span: SpanRecord, limits: SpanLimits = {}): SpanRecord

Applies span limits to a span record, truncating attributes, events, and links and counting drops.

Returns a new SpanRecord (the input is not mutated). Attribute count and value-length limits are enforced via limitAttributeEntries on the span and on each kept event and link; eventCountLimit and linkCountLimit cap the respective arrays, keeping the earliest entries. Every kind of drop is folded into the matching dropped*Count field, added to any count already present. Unlimited dimensions default to positive infinity, meaning "keep everything". Event and link arrays are only included in the output when the input had them.

import { applySpanLimits } from 'internal:opentelemetry/traces';

const limited = applySpanLimits(
  {
    traceId: '00000000000000000000000000000001',
    spanId: '0000000000000001',
    attributes: { a: 1, b: 2, c: 3 },
  },
  { attributeCountLimit: 2 },
);
limited.droppedAttributesCount; // 1

function getActiveSpan(): Span | undefined

Returns the Span currently marked active via runWithActiveSpan, or undefined.

This yields the live Span instance (so you can mutate it), distinct from getActiveSpanContext, which returns just the propagatable identity. Returns undefined outside any active-span scope.

import { getActiveSpan } from 'internal:opentelemetry/traces';

getActiveSpan()?.setAttribute('checkpoint', 'reached');

function getActiveSpanContext(): TraceContext | null

Returns the active trace context for propagation, merging explicit context, the active span, and baggage.

Resolution favors an explicit ActiveTelemetryContext (installed by instrumentation that extracted an upstream traceparent), defaulting its traceFlags to 1 and attaching the active baggage. Otherwise it derives the context from the active Span (flags 1). When neither exists it returns just the baggage-bearing context, or null if there is no baggage either. This is the getter registered with the common layer so other signals can correlate.

import { getActiveSpanContext } from 'internal:opentelemetry/traces';
import { W3CTraceContextPropagator } from 'internal:opentelemetry/common';

const ctx = getActiveSpanContext();
const headers: Record<string, unknown> = {};
if (ctx) new W3CTraceContextPropagator().inject(headers, ctx);

function getTracerProvider(): TracerProvider

Returns the effective tracer provider — the context-scoped one if set, otherwise the default.

Instrumentation should call this rather than caching a provider, so that a provider installed via runWithTracerProvider (or the process default set by setTracerProvider) is honored. A context value of null (from runWithoutTracerProvider) falls through to the default provider.

import { getTracerProvider } from 'internal:opentelemetry/traces';

const tracer = getTracerProvider().getTracer('my-lib');

function isScopedTraceTopic( name: string, phase: 'start' | 'end' | 'event' | 'attribute' | 'link' | 'status' | 'rename' ): boolean

Tests whether a topic name is the unversioned scope trace topic for a given phase.

Returns true only for names of the form otel:trace:<scope>:<phase> where <scope> is a single segment containing no @ (the version separator). This deliberately excludes versioned topics (otel:trace:<scope>@<version>:<phase>), so a consumer subscribing at the scope level can avoid double-counting records that also fan out to a versioned topic. Names not starting with otel:trace: or not ending with the expected phase suffix return false.

import { isScopedTraceTopic } from 'internal:opentelemetry/traces';

isScopedTraceTopic('otel:trace:orders:start', 'start');          // true
isScopedTraceTopic('otel:trace:orders@1.0.0:start', 'start');    // false

function isTracerProviderContextEnabled(): boolean

Reports whether a tracer provider is currently installed in the context (not suppressed).

Returns false inside a runWithoutTracerProvider scope (where the context value is null) and true when a provider has been set via runWithTracerProvider. Note it returns false when no context override exists at all, even though getTracerProvider would still yield the default.

import { runWithTracerProvider, TracerProvider, isTracerProviderContextEnabled } from 'internal:opentelemetry/traces';

runWithTracerProvider(new TracerProvider(), () => {
  isTracerProviderContextEnabled(); // true
});

function runWithActiveSpan<R>(span: Span, fn: () => R): R

Runs fn with span as the active span, so child spans inherit its trace and parent IDs.

Installs both the active-Span slot (for getActiveSpan) and a derived ActiveTelemetryContext (for getActiveSpanContext), inheriting traceFlags, traceState, and baggage from any surrounding context. When inherited baggage is present it is re-established for the callback. The scope unwinds when fn returns and propagates across awaits. Returns whatever fn returns.

import { getTracerProvider, runWithActiveSpan } from 'internal:opentelemetry/traces';

const tracer = getTracerProvider().getTracer('orders');
const parent = tracer.startSpan('orders.create');
await runWithActiveSpan(parent, async () => {
  const child = tracer.startSpan('orders.validate'); // parentSpanId = parent.spanId
  child.end();
});
parent.end();

function runWithTracerProvider<R>(provider: TracerProvider, fn: () => R): R

Runs fn with provider installed as the active tracer provider for the dynamic scope.

The override is restored when fn returns and propagates across async boundaries within the callback. Returns whatever fn returns.

import { runWithTracerProvider, TracerProvider, getTracerProvider } from 'internal:opentelemetry/traces';

const provider = new TracerProvider();
runWithTracerProvider(provider, () => {
  getTracerProvider() === provider; // true
});

function runWithoutTracerProvider<R>(fn: () => R): R

Runs fn with tracing suppressed, so getTracerProvider yields the default and context is disabled.

Sets the context provider to null for the callback's dynamic scope. Used by exporters to avoid instrumenting their own outbound telemetry traffic and creating feedback loops. Returns whatever fn returns.

import { runWithoutTracerProvider, isTracerProviderContextEnabled } from 'internal:opentelemetry/traces';

runWithoutTracerProvider(() => {
  isTracerProviderContextEnabled(); // false
});

function setTracerProvider(provider: TracerProvider): void

Replaces the process-wide default tracer provider.

Affects every call to getTracerProvider that is not inside a runWithTracerProvider scope. The SDK calls this during bootstrap to install a configured provider.

import { setTracerProvider, TracerProvider } from 'internal:opentelemetry/traces';
import { Resource } from 'internal:opentelemetry/common';

setTracerProvider(new TracerProvider({
  resource: new Resource({ 'service.name': 'orders' }),
}));

Interfaces

interface ActiveTelemetryContext extends TraceContext {

The trace context stored in the ambient async-context store as "currently active".

Structurally identical to TraceContext; the distinct name marks values that flow through runWithActiveContext/currentActiveTelemetryContext rather than across a wire boundary. Read the current one with currentActiveTelemetryContext.

import { runWithActiveContext } from 'internal:opentelemetry/common';
import type { ActiveTelemetryContext } from 'internal:opentelemetry/common';

const active: ActiveTelemetryContext = {
  traceId: '00000000000000000000000000000001',
  spanId: '0000000000000001',
  traceFlags: 1,
};
runWithActiveContext(active, () => doWork());

interface SamplingResult {

The decision a sampler returns for a candidate span.

sample is the drop/keep verdict. attributes are merged onto the span when kept (letting a sampler annotate its reasoning), and traceState lets the sampler amend the vendor trace state that propagates downstream.

import type { SamplingResult } from 'internal:opentelemetry/common';

const result: SamplingResult = {
  sample: true,
  attributes: { 'sampler.rate': 0.1 },
};

Properties

sample: boolean

sample property on SamplingResult.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SamplingResult['sample'];
attributes?: Attributes

attributes property on SamplingResult.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SamplingResult['attributes'];
traceState?: string

traceState property on SamplingResult.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SamplingResult['traceState'];

interface SpanEndOptions {

Options for ending a span.

attributes are merged into the span at end time and status sets its final status (a null status leaves the existing status untouched). Both optional.

import type { SpanEndOptions } from 'internal:opentelemetry/common';

const options: SpanEndOptions = {
  status: { code: 'ok' },
  attributes: { 'http.response.status_code': 200 },
};

Properties

attributes?: Attributes

attributes property on SpanEndOptions.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanEndOptions['attributes'];
status?: SpanStatus | null

status property on SpanEndOptions.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanEndOptions['status'];

interface SpanEventRecord {

A timestamped, named event recorded within a span's lifetime.

name is required; timeUnixNano defaults to the moment the event was added when omitted, and attributes carry structured detail. Exceptions are commonly recorded as an event named exception with exception.* attributes.

import type { SpanEventRecord } from 'internal:opentelemetry/common';

const event: SpanEventRecord = {
  name: 'cache.miss',
  attributes: { 'cache.key': 'user:42' },
};

Properties

name: string

name property on SpanEventRecord.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanEventRecord['name'];
attributes?: Attributes

attributes property on SpanEventRecord.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanEventRecord['attributes'];
timeUnixNano?: number

timeUnixNano property on SpanEventRecord.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanEventRecord['timeUnixNano'];
droppedAttributesCount?: number

droppedAttributesCount property on SpanEventRecord.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanEventRecord['droppedAttributesCount'];

interface SpanLimits {

Caps applied to a span's attributes, events, and links before export.

attributeCountLimit bounds how many attributes are kept (excess counted as dropped by limitAttributeEntries); attributeValueLengthLimit truncates long string values; eventCountLimit and linkCountLimit bound events and links. Omitting a field means unlimited for that dimension.

import type { SpanLimits } from 'internal:opentelemetry/common';

const limits: SpanLimits = {
  attributeCountLimit: 128,
  attributeValueLengthLimit: 1024,
};

Properties

attributeCountLimit?: number

attributeCountLimit property on SpanLimits.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanLimits['attributeCountLimit'];
attributeValueLengthLimit?: number

attributeValueLengthLimit property on SpanLimits.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanLimits['attributeValueLengthLimit'];
eventCountLimit?: number

eventCountLimit property on SpanLimits.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanLimits['eventCountLimit'];
linkCountLimit?: number

linkCountLimit property on SpanLimits.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanLimits['linkCountLimit'];

interface SpanLinkContext {

Minimal reference to another span that a link points at.

Identifies the linked span by its traceId and spanId (both required), optionally carrying that span's traceState and W3C flags. Extended with attributes by SpanLinkRecord.

import type { SpanLinkContext } from 'internal:opentelemetry/common';

const link: SpanLinkContext = {
  traceId: '00000000000000000000000000000002',
  spanId: '0000000000000002',
};

Properties

traceId: string

traceId property on SpanLinkContext.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanLinkContext['traceId'];
spanId: string

spanId property on SpanLinkContext.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanLinkContext['spanId'];
traceState?: string

traceState property on SpanLinkContext.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanLinkContext['traceState'];
flags?: number

flags property on SpanLinkContext.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanLinkContext['flags'];

interface SpanLinkRecord extends SpanLinkContext {

A span link enriched with its own attributes for export.

Adds an optional attributes bag and a droppedAttributesCount to the bare SpanLinkContext, matching the OTLP link shape. This is the form passed in SpanStartOptions.links and stored on a SpanRecord.

import type { SpanLinkRecord } from 'internal:opentelemetry/common';

const link: SpanLinkRecord = {
  traceId: '00000000000000000000000000000002',
  spanId: '0000000000000002',
  attributes: { 'link.kind': 'follows_from' },
};

Properties

attributes?: Attributes

attributes property on SpanLinkRecord.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanLinkRecord['attributes'];
droppedAttributesCount?: number

droppedAttributesCount property on SpanLinkRecord.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanLinkRecord['droppedAttributesCount'];

interface SpanRecord {

The full serialized shape of a span as it flows across topics and into exporters.

traceId and spanId are required; everything else is populated across the span lifecycle (start, attribute/event/link mutations, status, end). Timestamps are Unix nanoseconds, kind is the OTel span-kind string, and the dropped* counters record data lost to span limits. injectedHeaders snapshots any propagation headers written on the outbound side of an instrumented call.

import type { SpanRecord } from 'internal:opentelemetry/common';

const span: SpanRecord = {
  traceId: '00000000000000000000000000000001',
  spanId: '0000000000000001',
  name: 'GET /orders',
  kind: 'server',
  startTimeUnixNano: Date.now() * 1e6,
};

Properties

schemaVersion?: number

schemaVersion property on SpanRecord.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanRecord['schemaVersion'];
operation?: string

operation property on SpanRecord.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanRecord['operation'];
name?: string

name property on SpanRecord.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanRecord['name'];
traceId: string

traceId property on SpanRecord.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanRecord['traceId'];
spanId: string

spanId property on SpanRecord.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanRecord['spanId'];
parentSpanId?: string | null

parentSpanId property on SpanRecord.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanRecord['parentSpanId'];
traceState?: string

traceState property on SpanRecord.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanRecord['traceState'];
timeUnixNano?: number

timeUnixNano property on SpanRecord.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanRecord['timeUnixNano'];
startTimeUnixNano?: number

startTimeUnixNano property on SpanRecord.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanRecord['startTimeUnixNano'];
endTimeUnixNano?: number

endTimeUnixNano property on SpanRecord.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanRecord['endTimeUnixNano'];
attributes?: Attributes

attributes property on SpanRecord.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanRecord['attributes'];
scope?: ScopeInfo

scope property on SpanRecord.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanRecord['scope'];
resource?: Resource

resource property on SpanRecord.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanRecord['resource'];
kind?: string

kind property on SpanRecord.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanRecord['kind'];
status?: SpanStatus | null

status property on SpanRecord.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanRecord['status'];
events?: SpanEventRecord[]

events property on SpanRecord.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanRecord['events'];
droppedAttributesCount?: number

droppedAttributesCount property on SpanRecord.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanRecord['droppedAttributesCount'];
droppedEventsCount?: number

droppedEventsCount property on SpanRecord.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanRecord['droppedEventsCount'];
droppedLinksCount?: number

droppedLinksCount property on SpanRecord.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanRecord['droppedLinksCount'];
flags?: number

flags property on SpanRecord.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanRecord['flags'];
injectedHeaders?: Record<string, unknown>

injectedHeaders property on SpanRecord.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanRecord['injectedHeaders'];

interface SpanStartOptions {

Options for starting a span.

traceId and parentSpanId establish parentage explicitly (a null parent forces a new root even inside an active span); omitting them inherits the active context. attributes, links, and kind seed the span at start.

import type { SpanStartOptions } from 'internal:opentelemetry/common';

const options: SpanStartOptions = {
  kind: 'client',
  attributes: { 'db.system': 'postgresql' },
};

Properties

traceId?: string

traceId property on SpanStartOptions.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanStartOptions['traceId'];
parentSpanId?: string | null

parentSpanId property on SpanStartOptions.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanStartOptions['parentSpanId'];
attributes?: Attributes

attributes property on SpanStartOptions.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanStartOptions['attributes'];
kind?: string

kind property on SpanStartOptions.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanStartOptions['kind'];

interface SpanStatus {

Terminal status attached to a span at end time.

code is the OpenTelemetry status string (typically 'unset', 'ok', or 'error'); message supplies a human-readable description and is meaningful mainly for the error code. A null status on a span means status was never set and should be treated as unset.

import type { SpanStatus } from 'internal:opentelemetry/common';

const status: SpanStatus = { code: 'error', message: 'connection reset' };

Properties

code?: string

code property on SpanStatus.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanStatus['code'];
message?: string

message property on SpanStatus.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: SpanStatus['message'];

interface TraceContext {

Trace-context fields carried across a propagation boundary.

Every field is optional so the same shape describes both a fully-populated extracted context and a partial one under construction. traceId/spanId are lowercase hex, traceFlags is the one-byte W3C flags value (bit 0 = sampled), traceState is the raw vendor list, and baggage holds decoded W3C baggage.

import type { TraceContext } from 'internal:opentelemetry/common';

const ctx: TraceContext = {
  traceId: '00000000000000000000000000000001',
  spanId: '0000000000000001',
  traceFlags: 1,
};

Properties

traceId?: string

traceId property on TraceContext.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: TraceContext['traceId'];
spanId?: string

spanId property on TraceContext.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: TraceContext['spanId'];
traceFlags?: number

traceFlags property on TraceContext.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: TraceContext['traceFlags'];
traceState?: string

traceState property on TraceContext.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: TraceContext['traceState'];
baggage?: Baggage | null

baggage property on TraceContext.

Omitted optional values default to undefined; required values are expected from the producer before the record is exported or published. Consumers should tolerate missing optional fields in telemetry payloads.

let value: TraceContext['baggage'];