getCurrentSpanId()

Get the current span ID

Overview

getCurrentSpanId() returns the span ID of the currently active span. Useful for detailed logging, debugging, and correlating specific operations.

Signature

1getCurrentSpanId(): string | undefined

Basic Usage

1import { RespanTelemetry } from '@respan/tracing';
2
3const respanAi = new RespanTelemetry({
4 apiKey: process.env.RESPAN_API_KEY,
5 appName: 'my-app'
6});
7
8await respanAi.initialize();
9
10await respanAi.withTask(
11 { name: 'data_processing' },
12 async () => {
13 const client = respanAi.getClient();
14 const spanId = client.getCurrentSpanId();
15
16 console.log(`Processing in span: ${spanId}`);
17
18 return 'done';
19 }
20);

Trace and Span IDs Together

1await respanAi.withWorkflow(
2 { name: 'complex_workflow' },
3 async () => {
4 const client = respanAi.getClient();
5 const traceId = client.getCurrentTraceId();
6 const spanId = client.getCurrentSpanId();
7
8 console.log(`Trace: ${traceId}, Span: ${spanId}`);
9
10 await respanAi.withTask(
11 { name: 'subtask' },
12 async () => {
13 const subSpanId = client.getCurrentSpanId();
14 console.log(`Subtask Span: ${subSpanId}`);
15
16 return 'done';
17 }
18 );
19
20 return 'workflow_complete';
21 }
22);

Detailed Logging

1await respanAi.withAgent(
2 { name: 'research_agent' },
3 async () => {
4 const client = respanAi.getClient();
5
6 await respanAi.withTool(
7 { name: 'web_search' },
8 async () => {
9 const spanId = client.getCurrentSpanId();
10 console.log(`[Span:${spanId}] Executing web search`);
11
12 const results = await searchWeb('AI trends');
13
14 console.log(`[Span:${spanId}] Found ${results.length} results`);
15
16 return results;
17 }
18 );
19
20 return 'agent_complete';
21 }
22);

Error Context

1await respanAi.withTask(
2 { name: 'database_query' },
3 async () => {
4 const client = respanAi.getClient();
5 const spanId = client.getCurrentSpanId();
6
7 try {
8 return await db.query('SELECT * FROM users');
9 } catch (error) {
10 console.error(`[Span:${spanId}] Database query failed:`, error);
11 client.recordSpanException(error);
12 throw error;
13 }
14 }
15);

Return Value

Returns the current span ID as a string, or undefined if no span is active.

Best Practices

  • Use span IDs for granular operation tracking
  • Include span IDs in detailed logs for precise debugging
  • Combine with trace IDs for complete context
  • Only call within an active span (workflow, task, agent, or tool)
  • Different spans have different IDs, even within the same trace