0
# OpenTelemetry Core
1
2
OpenTelemetry Core provides foundational constants, utilities, and implementations shared by all OpenTelemetry SDK packages. It includes built-in propagators for W3C Trace Context and Baggage, time handling utilities, platform abstractions, and error handling infrastructure that enable context sharing across distributed services.
3
4
## Package Information
5
6
- **Package Name**: @opentelemetry/core
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @opentelemetry/core`
10
11
## Core Imports
12
13
```typescript
14
import {
15
W3CTraceContextPropagator,
16
W3CBaggagePropagator,
17
CompositePropagator,
18
TraceState,
19
AnchoredClock
20
} from "@opentelemetry/core";
21
```
22
23
For CommonJS:
24
25
```javascript
26
const {
27
W3CTraceContextPropagator,
28
W3CBaggagePropagator,
29
CompositePropagator,
30
TraceState,
31
AnchoredClock
32
} = require("@opentelemetry/core");
33
```
34
35
## Basic Usage
36
37
```typescript
38
import {
39
W3CTraceContextPropagator,
40
W3CBaggagePropagator,
41
CompositePropagator,
42
TraceState,
43
hrTime,
44
sanitizeAttributes
45
} from "@opentelemetry/core";
46
47
// Create a composite propagator
48
const propagator = new CompositePropagator({
49
propagators: [
50
new W3CTraceContextPropagator(),
51
new W3CBaggagePropagator(),
52
],
53
});
54
55
// Work with trace state
56
const traceState = new TraceState("key1=value1,key2=value2");
57
const updatedState = traceState.set("newkey", "newvalue");
58
59
// Get high-resolution time
60
const timestamp = hrTime();
61
62
// Sanitize attributes
63
const cleanAttrs = sanitizeAttributes({
64
"user.id": "12345",
65
"request.size": 1024,
66
"valid": true
67
});
68
```
69
70
## Architecture
71
72
OpenTelemetry Core is organized around several key architectural components:
73
74
- **Propagation System**: W3C-compliant propagators for trace context and baggage with compositional design
75
- **Time Management**: High-resolution timing utilities with nanosecond precision and monotonic clock support
76
- **Platform Abstraction**: Cross-platform utilities for environment access, performance measurement, and SDK information
77
- **Context Management**: Utilities for RPC metadata, trace suppression, and context manipulation
78
- **Validation & Sanitization**: Attribute validation, error handling, and data sanitization
79
- **Utility Functions**: Common utilities for merging, timeout handling, URL matching, and configuration parsing
80
81
## Capabilities
82
83
### Context Propagation
84
85
W3C-compliant propagators for distributed tracing and baggage propagation. Supports both trace context and baggage standards with compositional propagator patterns.
86
87
```typescript { .api }
88
class W3CTraceContextPropagator implements TextMapPropagator {
89
inject(context: Context, carrier: unknown, setter: TextMapSetter): void;
90
extract(context: Context, carrier: unknown, getter: TextMapGetter): Context;
91
fields(): string[];
92
}
93
94
class W3CBaggagePropagator implements TextMapPropagator {
95
inject(context: Context, carrier: unknown, setter: TextMapSetter): void;
96
extract(context: Context, carrier: unknown, getter: TextMapGetter): Context;
97
fields(): string[];
98
}
99
100
class CompositePropagator implements TextMapPropagator {
101
constructor(config?: CompositePropagatorConfig);
102
inject(context: Context, carrier: unknown, setter: TextMapSetter): void;
103
extract(context: Context, carrier: unknown, getter: TextMapGetter): Context;
104
fields(): string[];
105
}
106
```
107
108
[Context Propagation](./propagation.md)
109
110
### High-Resolution Timing
111
112
Nanosecond-precision timing utilities with monotonic clock support and various time format conversions. Essential for accurate span timing and performance measurement.
113
114
```typescript { .api }
115
class AnchoredClock implements Clock {
116
constructor(systemClock: Clock, monotonicClock: Clock);
117
now(): number;
118
}
119
120
function hrTime(performanceNow?: number): HrTime;
121
function hrTimeDuration(startTime: HrTime, endTime: HrTime): HrTime;
122
function hrTimeToNanoseconds(time: HrTime): number;
123
function hrTimeToMilliseconds(time: HrTime): number;
124
function hrTimeToMicroseconds(time: HrTime): number;
125
function millisToHrTime(epochMillis: number): HrTime;
126
```
127
128
[Timing Utilities](./timing.md)
129
130
### Trace State Management
131
132
W3C TraceState specification-compliant key-value store for vendor-specific trace information with immutable operations and serialization support.
133
134
```typescript { .api }
135
class TraceState implements api.TraceState {
136
constructor(rawTraceState?: string);
137
get(key: string): string | undefined;
138
set(key: string, value: string): TraceState;
139
unset(key: string): TraceState;
140
serialize(): string;
141
}
142
143
function parseTraceParent(traceParent: string): SpanContext | null;
144
```
145
146
[Trace State](./trace-state.md)
147
148
### Platform Utilities
149
150
Cross-platform abstractions for environment variable access, performance measurement, SDK information, and timer utilities that work across Node.js and browser environments.
151
152
```typescript { .api }
153
const SDK_INFO: object;
154
const _globalThis: object;
155
const otperformance: object;
156
157
function getBooleanFromEnv(key: string): boolean | undefined;
158
function getStringFromEnv(key: string): string | undefined;
159
function getNumberFromEnv(key: string): number | undefined;
160
function getStringListFromEnv(key: string, separator?: string): string[];
161
function unrefTimer(fn: Function, delay: number): any;
162
```
163
164
[Platform Utilities](./platform.md)
165
166
### Context Management
167
168
Utilities for managing RPC metadata, trace suppression, and context manipulation including support for disabling tracing in specific execution contexts.
169
170
```typescript { .api }
171
enum RPCType {
172
HTTP = 'http'
173
}
174
175
function setRPCMetadata(context: Context, meta: RPCMetadata): Context;
176
function getRPCMetadata(context: Context): RPCMetadata | undefined;
177
function deleteRPCMetadata(context: Context): Context;
178
179
function suppressTracing(context: Context): Context;
180
function unsuppressTracing(context: Context): Context;
181
function isTracingSuppressed(context: Context): boolean;
182
```
183
184
[Context Management](./context.md)
185
186
### Data Validation & Error Handling
187
188
Attribute validation, sanitization, and comprehensive error handling infrastructure with global error handler support and logging integration.
189
190
```typescript { .api }
191
function sanitizeAttributes(attributes: unknown): Attributes;
192
function isAttributeValue(val: unknown): val is AttributeValue;
193
194
function setGlobalErrorHandler(handler: ErrorHandler): void;
195
function globalErrorHandler(ex: Exception): void;
196
function loggingErrorHandler(): ErrorHandler;
197
198
enum ExportResultCode {
199
SUCCESS,
200
FAILED
201
}
202
203
interface ExportResult {
204
code: ExportResultCode;
205
error?: Error;
206
}
207
```
208
209
[Validation & Error Handling](./validation.md)
210
211
### Utility Functions
212
213
Common utility functions including deep object merging, timeout handling, URL pattern matching, and configuration parsing that support various SDK operations.
214
215
```typescript { .api }
216
function merge(...args: any[]): any;
217
218
class TimeoutError extends Error {}
219
function callWithTimeout<T>(promise: Promise<T>, timeout: number): Promise<T>;
220
221
function urlMatches(url: string, urlToMatch: string | RegExp): boolean;
222
function isUrlIgnored(url: string, ignoredUrls?: Array<string | RegExp>): boolean;
223
224
class BindOnceFuture<R, This, T> {
225
constructor(callback: T, that: This);
226
isCalled: boolean;
227
promise: Promise<R>;
228
call(...args: Parameters<T>): Promise<R>;
229
}
230
```
231
232
[Utility Functions](./utilities.md)
233
234
## Types
235
236
```typescript { .api }
237
interface Clock {
238
now(): number;
239
}
240
241
interface InstrumentationScope {
242
readonly name: string;
243
readonly version?: string;
244
readonly schemaUrl?: string;
245
}
246
247
type ErrorHandler = (ex: Exception) => void;
248
249
interface CompositePropagatorConfig {
250
propagators?: TextMapPropagator[];
251
}
252
253
type HTTPMetadata = {
254
type: RPCType.HTTP;
255
route?: string;
256
span: Span;
257
};
258
259
type RPCMetadata = HTTPMetadata;
260
```