getCurrentTraceId()

Get the current trace ID

Overview

getCurrentTraceId() returns the trace ID of the currently active trace. Useful for correlating logs, passing to external systems, or debugging.

Signature

1getCurrentTraceId(): 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.withWorkflow(
11 { name: 'user_request' },
12 async () => {
13 const client = respanAi.getClient();
14 const traceId = client.getCurrentTraceId();
15
16 console.log(`Processing trace: ${traceId}`);
17
18 return traceId;
19 }
20);

Log Correlation

1await respanAi.withWorkflow(
2 { name: 'api_request' },
3 async () => {
4 const client = respanAi.getClient();
5 const traceId = client.getCurrentTraceId();
6
7 // Add trace ID to logs for correlation
8 console.log(`[${traceId}] Starting API request`);
9
10 const result = await fetch('https://api.example.com/data');
11
12 console.log(`[${traceId}] API request completed`);
13
14 return result;
15 }
16);

Pass to External Systems

1await respanAi.withWorkflow(
2 { name: 'payment_processing' },
3 async () => {
4 const client = respanAi.getClient();
5 const traceId = client.getCurrentTraceId();
6
7 // Pass trace ID to payment processor for correlation
8 const payment = await processPayment({
9 amount: 100,
10 currency: 'USD',
11 trace_id: traceId // Include for debugging
12 });
13
14 return payment;
15 }
16);

Return to User

1import express from 'express';
2
3app.post('/api/process', async (req, res) => {
4 await respanAi.withWorkflow(
5 { name: 'api_endpoint' },
6 async () => {
7 const client = respanAi.getClient();
8 const traceId = client.getCurrentTraceId();
9
10 const result = await processRequest(req.body);
11
12 // Return trace ID to user for support requests
13 res.json({
14 success: true,
15 result: result,
16 trace_id: traceId
17 });
18 }
19 );
20});

Return Value

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

Best Practices

  • Use trace IDs for log correlation across services
  • Include trace IDs in API responses for debugging
  • Pass trace IDs to external systems for end-to-end tracing
  • Store trace IDs with error reports for troubleshooting
  • Only call within an active trace (workflow, task, agent, or tool)