getClient()

Access the Respan client for span and trace operations

Overview

getClient() returns the tracing client instance for manual span operations. Use it to read IDs, update spans, add events, and manage traces.

Signature

1getClient(): RespanClient

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
15 // Get current trace and span IDs
16 const traceId = client.getCurrentTraceId();
17 const spanId = client.getCurrentSpanId();
18
19 console.log(`Processing in trace ${traceId}, span ${spanId}`);
20
21 // Add event
22 client.addSpanEvent('processing_started', {
23 records: 100
24 });
25
26 // Your processing logic
27 return 'processed';
28 }
29);

Update Current Span

1await respanAi.withWorkflow(
2 { name: 'user_request' },
3 async () => {
4 const client = respanAi.getClient();
5
6 // Update span with custom attributes
7 client.updateCurrentSpan({
8 respan_params: {
9 customer_identifier: 'user-123',
10 metadata: {
11 environment: 'production',
12 version: '2.0'
13 }
14 },
15 attributes: {
16 'custom.status': 'in_progress'
17 }
18 });
19
20 return await processRequest();
21 }
22);

Record Exceptions

1await respanAi.withTask(
2 { name: 'risky_operation' },
3 async () => {
4 const client = respanAi.getClient();
5
6 try {
7 return await riskyApiCall();
8 } catch (error) {
9 // Manually record exception
10 client.recordSpanException(error);
11 throw error;
12 }
13 }
14);

Add Events

1await respanAi.withWorkflow(
2 { name: 'batch_processing' },
3 async () => {
4 const client = respanAi.getClient();
5
6 client.addSpanEvent('batch_started', {
7 batch_size: 1000
8 });
9
10 for (let i = 0; i < 10; i++) {
11 await processBatch(i);
12 client.addSpanEvent('batch_completed', {
13 batch_number: i,
14 records_processed: 100
15 });
16 }
17
18 client.addSpanEvent('all_batches_completed');
19
20 return 'done';
21 }
22);

Available Client Methods

MethodDescription
getCurrentTraceId()Get the current trace ID
getCurrentSpanId()Get the current span ID
updateCurrentSpan()Update span attributes, status, metadata
addSpanEvent()Add a timestamped event to current span
recordSpanException()Record an error on current span
getContextValue()Get a context value by key
setContextValue()Set a context value by key
isRecording()Check if tracing is currently active
getTracer()Get the underlying OpenTelemetry tracer
flush()Manually flush pending spans

Best Practices

  • Use getClient() within traced functions (workflow, task, agent, tool)
  • Call client methods only when a span is active
  • Add events for significant milestones in your logic
  • Record exceptions for better error tracking
  • Update spans with custom metadata for filtering and analysis