Creates and starts a new span, sets it as the active span in the current context, and executes a provided function within this context.
This method creates a span, makes it active during the execution of the provided function, and automatically ends the span when the function completes (or throws). This provides automatic span lifecycle management and context propagation.
The name of the span, should be descriptive of the operation being traced
The function to execute within the span's active context
The result of executing the provided function
// Synchronous operation with just name and function
const result = tracer.startActiveSpan('user-service', (span) => {
span.setAttribute('operation', 'get-user-details');
return { user: getUserData(), timestamp: new Date().toISOString() };
});
// With options
const result2 = tracer.startActiveSpan('database-query',
{ attributes: { 'db.table': 'users' } },
(span) => {
span.setAttribute('db.operation', 'SELECT');
return database.getUser('123');
}
);
// With full context control
const result3 = tracer.startActiveSpan('external-api',
{ attributes: { 'service.name': 'payment-api' } },
currentContext,
async (span) => {
try {
const response = await fetch('/api/payment');
span.setAttributes({
'http.status_code': response.status,
'operation.success': response.ok
});
return response.json();
} catch (error) {
span.setAttribute('error.type', error.constructor.name);
throw error; // Error automatically recorded
}
}
);
Creates and starts a new span without setting it as the active span in the current context.
This method creates a span but does NOT modify the current execution context.
The caller is responsible for managing the span's lifecycle, including calling end()
when the operation completes.
The name of the span, should be descriptive of the operation being traced
Optionaloptions: IOTelSpanOptionsOptional configuration for span creation (parent context, attributes, etc.)
The newly created span, or null if span creation failed
span.end()startActiveSpan if you want automatic context managementconst span = tracer.startSpan('database-operation');
if (span) {
try {
span.setAttribute('db.table', 'users');
span.setAttribute('db.operation', 'SELECT');
// Perform database operation
const result = await db.query('SELECT * FROM users');
span.setAttributes({
'db.rows_affected': result.length,
'operation.success': true
});
} catch (error) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: error.message
});
span.recordException(error);
} finally {
span.end(); // Always end the span
}
}
OpenTelemetry tracer interface for creating and managing spans within a trace.
A tracer is responsible for creating spans that represent units of work within a distributed system. Each tracer is typically associated with a specific instrumentation library or component, allowing for fine-grained control over how different parts of an application generate telemetry.
Example
See
Since
3.4.0