Function: withSpan()
@arolariu/website / instrumentation.server / withSpan
Function: withSpan()
withSpan<
T>(spanName,fn,attributes?):Promise<T>
Defined in: instrumentation.server.ts:991
Executes a function within a traced span with automatic lifecycle management.
This is the recommended way to create spans for async operations. It handles span creation with context propagation, automatic success/error status setting, exception recording, span cleanup, and end timing.
Type Parameters
T
T
Return type of the function
Parameters
spanName
Name of the span following semantic conventions (e.g., "http.server.request", "db.query")
fn
(span) => Promise<T>
Async function to execute within the span. Receives the span for adding attributes/events
attributes?
Optional type-safe attributes to set on span creation
Returns
Promise<T>
Promise resolving to the function's return value
Throws
Re-throws any error from the function after recording it in the span
Remarks
- Span name must follow the
SpanOperationTypepattern for type safety - Use dot notation for hierarchical naming (e.g., "http.client.request")
- Add high-cardinality data as events, not attributes
- The span is available in the callback for adding dynamic attributes
Examples
// API route with HTTP attributes
const result = await withSpan('api.user.get', async (span) => {
return await fetchUser(userId);
}, {
'http.method': 'GET',
'http.status_code': 200,
'next.render_context': 'api',
});
// Database operation with semantic attributes
const data = await withSpan(
'db.query',
async (span) => {
span.addEvent('query.start');
const result = await db.query(sql);
span.addEvent('query.complete', { rows: result.length });
return result;
},
{
'db.system': 'postgresql',
'db.operation': 'SELECT',
'db.collection': 'users',
}
);
// Next.js Server Component rendering
const content = await withSpan('component.UserProfile', async (span) => {
return await renderUserProfile();
}, {
'next.render_context': 'server',
'next.server_components': true,
});