0
# Tracer Provider
1
2
The tracer provider serves as the central registry and factory for creating tracers with shared configuration across an OpenTelemetry application. It manages the lifecycle of tracers, span processors, and provides controlled shutdown capabilities.
3
4
## Capabilities
5
6
### BasicTracerProvider
7
8
The main tracer provider implementation that platform libraries can extend. It provides tracer creation, configuration management, and coordinated shutdown of all components.
9
10
```typescript { .api }
11
/**
12
* Basic tracer provider which platform libraries can extend
13
*/
14
class BasicTracerProvider implements TracerProvider {
15
constructor(config?: TracerConfig);
16
17
/**
18
* Get a tracer with the given name and optional version/schema URL
19
* Returns cached tracer for same name/version/schemaUrl combination
20
*/
21
getTracer(name: string, version?: string, options?: { schemaUrl?: string }): Tracer;
22
23
/**
24
* Force flush all span processors within the configured timeout
25
* @returns Promise that resolves when all processors have flushed
26
*/
27
forceFlush(): Promise<void>;
28
29
/**
30
* Shutdown all active span processors
31
* @returns Promise that resolves when shutdown is complete
32
*/
33
shutdown(): Promise<void>;
34
}
35
36
/**
37
* Configuration interface for Basic Tracer
38
*/
39
interface TracerConfig {
40
/** Sampler determines if a span should be recorded or should be a NoopSpan */
41
sampler?: Sampler;
42
43
/** General Limits for attributes across the trace service */
44
generalLimits?: GeneralLimits;
45
46
/** Span-specific limits for attributes, events, and links */
47
spanLimits?: SpanLimits;
48
49
/** Resource associated with trace telemetry */
50
resource?: Resource;
51
52
/** Generator of trace and span IDs (defaults to random ID generator) */
53
idGenerator?: IdGenerator;
54
55
/** How long forceFlush can run before being cancelled (default: 30000ms) */
56
forceFlushTimeoutMillis?: number;
57
58
/** List of SpanProcessors for the tracer */
59
spanProcessors?: SpanProcessor[];
60
}
61
```
62
63
**Usage Examples:**
64
65
```typescript
66
import { BasicTracerProvider, BatchSpanProcessor, ConsoleSpanExporter, AlwaysOnSampler } from '@opentelemetry/sdk-trace-base';
67
import { Resource } from '@opentelemetry/resources';
68
69
// Basic provider setup
70
const provider = new BasicTracerProvider({
71
resource: new Resource({
72
'service.name': 'my-service',
73
'service.version': '1.0.0',
74
}),
75
sampler: new AlwaysOnSampler(),
76
spanProcessors: [
77
new BatchSpanProcessor(new ConsoleSpanExporter())
78
],
79
forceFlushTimeoutMillis: 5000
80
});
81
82
// Get tracers with different configurations
83
const userTracer = provider.getTracer('user-service', '2.1.0');
84
const orderTracer = provider.getTracer('order-service', '1.5.0', {
85
schemaUrl: 'https://opentelemetry.io/schemas/1.21.0'
86
});
87
88
// Graceful shutdown
89
await provider.forceFlush();
90
await provider.shutdown();
91
```
92
93
### Configuration Types
94
95
Configuration interfaces for setting limits and controlling tracer behavior.
96
97
```typescript { .api }
98
/**
99
* Global configuration limits of trace service
100
*/
101
interface GeneralLimits {
102
/** Maximum allowed attribute value size */
103
attributeValueLengthLimit?: number;
104
/** Number of attributes per trace */
105
attributeCountLimit?: number;
106
}
107
108
/**
109
* Span-specific configuration limits
110
*/
111
interface SpanLimits {
112
/** Maximum allowed attribute value size for spans */
113
attributeValueLengthLimit?: number;
114
/** Number of attributes per span */
115
attributeCountLimit?: number;
116
/** Number of links per span */
117
linkCountLimit?: number;
118
/** Number of message events per span */
119
eventCountLimit?: number;
120
/** Maximum number of attributes allowed per span event */
121
attributePerEventCountLimit?: number;
122
/** Maximum number of attributes allowed per span link */
123
attributePerLinkCountLimit?: number;
124
}
125
126
/**
127
* Configuration for registering the API with the SDK
128
*/
129
interface SDKRegistrationConfig {
130
/** Propagator to register as the global propagator */
131
propagator?: TextMapPropagator | null;
132
/** Context manager to register as the global context manager */
133
contextManager?: ContextManager | null;
134
}
135
```
136
137
**Environment Variables:**
138
139
The tracer provider respects the following environment variables for configuration:
140
141
- `OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT` - Global attribute value length limit
142
- `OTEL_ATTRIBUTE_COUNT_LIMIT` - Global attribute count limit
143
- `OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT` - Span-specific attribute value length limit
144
- `OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT` - Span-specific attribute count limit
145
- `OTEL_SPAN_LINK_COUNT_LIMIT` - Maximum number of links per span
146
- `OTEL_SPAN_EVENT_COUNT_LIMIT` - Maximum number of events per span
147
- `OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT` - Max attributes per event
148
- `OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT` - Max attributes per link
149
150
**Usage Examples:**
151
152
```typescript
153
// Configuration with limits
154
const provider = new BasicTracerProvider({
155
generalLimits: {
156
attributeValueLengthLimit: 1024,
157
attributeCountLimit: 64
158
},
159
spanLimits: {
160
attributeValueLengthLimit: 512,
161
attributeCountLimit: 32,
162
linkCountLimit: 128,
163
eventCountLimit: 128,
164
attributePerEventCountLimit: 16,
165
attributePerLinkCountLimit: 16
166
}
167
});
168
169
// With custom resource and sampler
170
const provider = new BasicTracerProvider({
171
resource: new Resource({
172
'service.name': 'payment-service',
173
'service.namespace': 'production',
174
'deployment.environment': 'prod'
175
}),
176
sampler: new TraceIdRatioBasedSampler(0.1), // 10% sampling
177
forceFlushTimeoutMillis: 10000
178
});
179
```
180
181
### Tracer Implementation
182
183
Internal tracer implementation that creates and manages spans (not directly exported but important for understanding behavior).
184
185
```typescript { .api }
186
/**
187
* Tracer implementation that creates spans with sampling decisions
188
*/
189
interface Tracer {
190
/**
191
* Start a new span with optional configuration
192
*/
193
startSpan(name: string, options?: SpanOptions, context?: Context): Span;
194
195
/**
196
* Start an active span and execute a function within its context
197
* Multiple overloads support different parameter combinations
198
*/
199
startActiveSpan<F extends (span: Span) => ReturnType<F>>(
200
name: string,
201
fn: F
202
): ReturnType<F>;
203
204
startActiveSpan<F extends (span: Span) => ReturnType<F>>(
205
name: string,
206
options: SpanOptions,
207
fn: F
208
): ReturnType<F>;
209
210
startActiveSpan<F extends (span: Span) => ReturnType<F>>(
211
name: string,
212
options: SpanOptions,
213
context: Context,
214
fn: F
215
): ReturnType<F>;
216
217
/** Get the general limits configuration */
218
getGeneralLimits(): GeneralLimits;
219
220
/** Get the span limits configuration */
221
getSpanLimits(): SpanLimits;
222
}
223
```
224
225
### Force Flush Behavior
226
227
The BasicTracerProvider implements sophisticated force flush behavior with timeout handling.
228
229
```typescript { .api }
230
/**
231
* Internal enum for tracking force flush state
232
*/
233
enum ForceFlushState {
234
'resolved',
235
'timeout',
236
'error',
237
'unresolved'
238
}
239
```
240
241
**Force Flush Process:**
242
1. Calls `forceFlush()` on all configured span processors
243
2. Each processor flush is wrapped with a timeout based on `forceFlushTimeoutMillis`
244
3. If any processor exceeds the timeout, an error is logged but other processors continue
245
4. Returns a Promise that resolves when all processors complete or timeout
246
247
**Usage Examples:**
248
249
```typescript
250
// Force flush with custom timeout handling
251
try {
252
await provider.forceFlush();
253
console.log('All spans successfully flushed');
254
} catch (error) {
255
console.error('Some processors failed to flush:', error);
256
}
257
258
// Graceful application shutdown
259
async function gracefulShutdown() {
260
console.log('Starting graceful shutdown...');
261
262
try {
263
// Force flush pending spans
264
await provider.forceFlush();
265
266
// Shutdown all processors
267
await provider.shutdown();
268
269
console.log('Shutdown complete');
270
} catch (error) {
271
console.error('Shutdown error:', error);
272
}
273
}
274
275
process.on('SIGTERM', gracefulShutdown);
276
process.on('SIGINT', gracefulShutdown);
277
```