ReadonlyattribThe attribute container associated with this span, providing advanced attribute management capabilities. Rather than using the IReadableSpan#attributes directly which returns a readonly IOTelAttributes map that is a snapshot of the attributes at the time of access, the attribute container offers methods to get, set, delete, and iterate over attributes with fine-grained control. It is recommended that you only access the IReadableSpan#attributes property sparingly due to the performance cost of taking a snapshot of all attributes.
ReadonlyattributesProvides a snapshot of the span's attributes at the time this span was ended.
ReadonlydroppedReadonlydurationReadonlyendedReadonlyendReadonlykindIdentifies the type (or kind) that this span is representing.
ReadonlynameThe span's unique identifier.
Optional ReadonlyparentOptional ReadonlyparentReadonlyspanReturns the span context object associated with this span.
The span context is an immutable, serializable identifier that uniquely identifies this span within a trace. It contains the trace ID, span ID, and trace flags that can be used to create new child spans or propagate trace context across process boundaries.
The returned span context remains valid even after the span has ended, making it useful for asynchronous operations and cross-service communication.
The immutable span context associated with this span
const span = tracer.startSpan('parent-operation');
const spanContext = span.spanContext();
// Use context to create child spans in other parts of the system
const childSpan = tracer.startSpan('child-operation', {
parent: spanContext
});
// Context can be serialized for cross-service propagation
const traceId = spanContext.traceId;
const spanId = spanContext.spanId;
ReadonlystartReadonlystatusMarks the end of the span's execution and records the end timestamp.
This method finalizes the span and makes it available for export to tracing systems. Once ended, the span should not be used for further operations. The span's duration is calculated from its start time to the end time provided or current time.
OptionalendTime: OTelTimeInputOptional end time; if not provided, current time is used
this to discourage chaining after span completionconst span = tracer.startSpan('file-processing');
try {
// Perform the operation
const result = await processFile(filePath);
// Record success
span.setStatus({ code: SpanStatusCode.OK });
span.setAttribute('file.size', result.size);
} catch (error) {
span.recordException(error);
span.setStatus({
code: SpanStatusCode.ERROR,
message: error.message
});
} finally {
// Always end the span
span.end();
// Don't use span after this point
}
// Custom end time example
const customEndTime = Date.now() * 1000000; // nanoseconds
span.end(customEndTime);
Returns whether this span is actively recording information.
A recording span accepts and stores attributes, events, status, and other span data. Non-recording spans (typically due to sampling decisions) may ignore operations like setAttribute() to optimize performance. This method allows conditional logic to avoid expensive operations on non-recording spans.
True if the span is actively recording information, false otherwise
const span = tracer.startSpan('data-processing');
// Only perform expensive operations if span is recording
if (span.isRecording()) {
const metadata = await expensiveMetadataCalculation();
span.setAttributes({
'process.metadata': JSON.stringify(metadata),
'process.complexity': metadata.complexity,
'process.estimated_duration': metadata.estimatedMs
});
}
// Always safe to set basic attributes
span.setAttribute('process.started', true);
Records an exception as a span event with automatic error status handling.
This method captures exception information and automatically creates a span event with standardized exception attributes. It's the recommended way to handle errors within spans, providing consistent error reporting across the application.
The exception to record; accepts string messages or Error objects
Optionaltime: OTelTimeInputOptional timestamp for when the exception occurred; defaults to current time
const span = tracer.startSpan('risky-operation');
try {
await performRiskyOperation();
span.setStatus({ code: SpanStatusCode.OK });
} catch (error) {
// Record the exception details
span.recordException(error);
// Explicitly set error status
span.setStatus({
code: SpanStatusCode.ERROR,
message: 'Operation failed due to: ' + error.message
});
// Re-throw if needed
throw error;
} finally {
span.end();
}
// Recording string exceptions
span.recordException('Custom error message occurred');
// Recording with custom timestamp
const errorTime = Date.now() * 1000000; // nanoseconds
span.recordException(error, errorTime);
Sets a single attribute on the span with the specified key and value.
Attributes provide contextual information about the operation represented by the span. They are key-value pairs that help with filtering, grouping, and understanding spans in trace analysis tools. Attributes should represent meaningful properties of the operation.
The attribute key, should be descriptive and follow naming conventions
The attribute value; null or undefined values are invalid and result in undefined behavior
This span instance for method chaining
const span = tracer.startSpan('http-request');
// Set individual attributes with descriptive keys
span.setAttribute('http.method', 'POST')
.setAttribute('http.url', 'https://api.example.com/users')
.setAttribute('http.status_code', 201)
.setAttribute('user.id', '12345')
.setAttribute('request.size', 1024);
Sets multiple attributes on the span at once using an attributes object.
This method allows efficient batch setting of multiple attributes in a single call. All attributes in the provided object will be added to the span, supplementing any existing attributes (duplicate keys will be overwritten).
An object containing key-value pairs to set as span attributes
This span instance for method chaining
Sets the status of the span to indicate the success or failure of the operation.
The span status provides a standardized way to indicate whether the operation completed successfully, encountered an error, or is in an unknown state. This status is used by observability tools to provide meaningful insights about system health and operation outcomes.
The status object containing code and optional message
This span instance for method chaining
const span = tracer.startSpan('payment-processing');
try {
const result = await processPayment(paymentData);
// Indicate successful completion
span.setStatus({
code: SpanStatusCode.OK
});
} catch (error) {
// Indicate operation failed
span.setStatus({
code: SpanStatusCode.ERROR,
message: 'Payment processing failed: ' + error.message
});
span.recordException(error);
}
Updates the name of the span, overriding the name provided during creation.
Span names should be descriptive and represent the operation being performed. Updating the name can be useful when the operation's scope becomes clearer during execution, or when implementing generic spans that need specific naming based on runtime conditions.
The new name for the span, should be descriptive of the operation
This span instance for method chaining
const span = tracer.startSpan('generic-operation');
// Update name based on runtime determination
if (operationType === 'user-registration') {
span.updateName('user-registration');
span.setAttribute('operation.type', 'registration');
} else if (operationType === 'user-login') {
span.updateName('user-authentication');
span.setAttribute('operation.type', 'authentication');
}
Provides an OpenTelemetry compatible Interface for the Open Telemetry Sdk-Trace-Base (1.8.0 and 2.0.0) ReadableSpan type.
The IReadableSpan interface is used to represent a span that can be read and exported, while the OpenTelemetry specification defines a ReadableSpan as a Span that has been ended and is ready to be exported. By default all spans created by this library implement the IReadableSpan interface which also extends the IOTelSpan interface.
This interface is defined to provide compatibility with exporters defined by the OpenTelemetry Trace SDK.
Since
3.4.0