@aztec-labs/telemetry-client 6.0.0-nightly.20260829

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/dest/attributes.d.ts +143 -0
  2. package/dest/attributes.d.ts.map +1 -0
  3. package/dest/attributes.js +91 -0
  4. package/dest/bench.d.ts +34 -0
  5. package/dest/bench.d.ts.map +1 -0
  6. package/dest/bench.js +115 -0
  7. package/dest/config.d.ts +21 -0
  8. package/dest/config.d.ts.map +1 -0
  9. package/dest/config.js +85 -0
  10. package/dest/index.d.ts +12 -0
  11. package/dest/index.d.ts.map +1 -0
  12. package/dest/index.js +11 -0
  13. package/dest/json_rpc_server_metrics.d.ts +27 -0
  14. package/dest/json_rpc_server_metrics.d.ts.map +1 -0
  15. package/dest/json_rpc_server_metrics.js +154 -0
  16. package/dest/l1_metrics.d.ts +17 -0
  17. package/dest/l1_metrics.d.ts.map +1 -0
  18. package/dest/l1_metrics.js +54 -0
  19. package/dest/lmdb_metrics.d.ts +18 -0
  20. package/dest/lmdb_metrics.d.ts.map +1 -0
  21. package/dest/lmdb_metrics.js +34 -0
  22. package/dest/metric-utils.d.ts +24 -0
  23. package/dest/metric-utils.d.ts.map +1 -0
  24. package/dest/metric-utils.js +59 -0
  25. package/dest/metrics.d.ts +338 -0
  26. package/dest/metrics.d.ts.map +1 -0
  27. package/dest/metrics.js +1702 -0
  28. package/dest/monitored_batch_span_processor.d.ts +33 -0
  29. package/dest/monitored_batch_span_processor.d.ts.map +1 -0
  30. package/dest/monitored_batch_span_processor.js +111 -0
  31. package/dest/nodejs_metrics_monitor.d.ts +19 -0
  32. package/dest/nodejs_metrics_monitor.d.ts.map +1 -0
  33. package/dest/nodejs_metrics_monitor.js +115 -0
  34. package/dest/noop.d.ts +19 -0
  35. package/dest/noop.d.ts.map +1 -0
  36. package/dest/noop.js +104 -0
  37. package/dest/otel.d.ts +43 -0
  38. package/dest/otel.d.ts.map +1 -0
  39. package/dest/otel.js +537 -0
  40. package/dest/otel_filter_metric_exporter.d.ts +20 -0
  41. package/dest/otel_filter_metric_exporter.d.ts.map +1 -0
  42. package/dest/otel_filter_metric_exporter.js +67 -0
  43. package/dest/otel_logger_provider.d.ts +4 -0
  44. package/dest/otel_logger_provider.d.ts.map +1 -0
  45. package/dest/otel_logger_provider.js +25 -0
  46. package/dest/otel_propagation.d.ts +6 -0
  47. package/dest/otel_propagation.d.ts.map +1 -0
  48. package/dest/otel_propagation.js +102 -0
  49. package/dest/otel_resource.d.ts +3 -0
  50. package/dest/otel_resource.d.ts.map +1 -0
  51. package/dest/otel_resource.js +53 -0
  52. package/dest/prom_otel_adapter.d.ts +176 -0
  53. package/dest/prom_otel_adapter.d.ts.map +1 -0
  54. package/dest/prom_otel_adapter.js +292 -0
  55. package/dest/start.d.ts +7 -0
  56. package/dest/start.d.ts.map +1 -0
  57. package/dest/start.js +25 -0
  58. package/dest/telemetry.d.ts +149 -0
  59. package/dest/telemetry.d.ts.map +1 -0
  60. package/dest/telemetry.js +139 -0
  61. package/dest/vendor/attributes.d.ts +6 -0
  62. package/dest/vendor/attributes.d.ts.map +1 -0
  63. package/dest/vendor/attributes.js +6 -0
  64. package/dest/vendor/otel-pino-stream.d.ts +40 -0
  65. package/dest/vendor/otel-pino-stream.d.ts.map +1 -0
  66. package/dest/vendor/otel-pino-stream.js +229 -0
  67. package/dest/with_tracer.d.ts +33 -0
  68. package/dest/with_tracer.d.ts.map +1 -0
  69. package/dest/with_tracer.js +32 -0
  70. package/dest/wrappers/fetch.d.ts +16 -0
  71. package/dest/wrappers/fetch.d.ts.map +1 -0
  72. package/dest/wrappers/fetch.js +42 -0
  73. package/dest/wrappers/index.d.ts +3 -0
  74. package/dest/wrappers/index.d.ts.map +1 -0
  75. package/dest/wrappers/index.js +2 -0
  76. package/dest/wrappers/json_rpc_server.d.ts +4 -0
  77. package/dest/wrappers/json_rpc_server.d.ts.map +1 -0
  78. package/dest/wrappers/json_rpc_server.js +16 -0
  79. package/package.json +95 -0
  80. package/src/attributes.ts +174 -0
  81. package/src/bench.ts +168 -0
  82. package/src/config.ts +135 -0
  83. package/src/index.ts +11 -0
  84. package/src/json_rpc_server_metrics.ts +150 -0
  85. package/src/l1_metrics.ts +64 -0
  86. package/src/lmdb_metrics.ts +45 -0
  87. package/src/metric-utils.ts +75 -0
  88. package/src/metrics.ts +1802 -0
  89. package/src/monitored_batch_span_processor.ts +147 -0
  90. package/src/nodejs_metrics_monitor.ts +135 -0
  91. package/src/noop.ts +152 -0
  92. package/src/otel.ts +482 -0
  93. package/src/otel_filter_metric_exporter.ts +80 -0
  94. package/src/otel_logger_provider.ts +31 -0
  95. package/src/otel_propagation.ts +107 -0
  96. package/src/otel_resource.ts +71 -0
  97. package/src/prom_otel_adapter.ts +450 -0
  98. package/src/start.ts +42 -0
  99. package/src/telemetry.ts +348 -0
  100. package/src/vendor/attributes.ts +6 -0
  101. package/src/vendor/otel-pino-stream.ts +279 -0
  102. package/src/with_tracer.ts +35 -0
  103. package/src/wrappers/fetch.ts +50 -0
  104. package/src/wrappers/index.ts +2 -0
  105. package/src/wrappers/json_rpc_server.ts +26 -0
@@ -0,0 +1,348 @@
1
+ import {
2
+ type AttributeValue,
3
+ type BatchObservableCallback,
4
+ type Context,
5
+ type MetricOptions,
6
+ type Observable,
7
+ type BatchObservableResult as OtelBatchObservableResult,
8
+ type Gauge as OtelGauge,
9
+ type Histogram as OtelHistogram,
10
+ type ObservableGauge as OtelObservableGauge,
11
+ type ObservableResult as OtelObservableResult,
12
+ type ObservableUpDownCounter as OtelObservableUpDownCounter,
13
+ type UpDownCounter as OtelUpDownCounter,
14
+ type Span,
15
+ SpanStatusCode,
16
+ type Tracer,
17
+ } from '@opentelemetry/api';
18
+
19
+ import type * as Attributes from './attributes.js';
20
+ import type { MetricDefinition } from './metrics.js';
21
+ import { getTelemetryClient } from './start.js';
22
+ import type * as VendorAttributes from './vendor/attributes.js';
23
+
24
+ export { toMetricOptions, createUpDownCounterWithDefault } from './metric-utils.js';
25
+
26
+ export { type Span, SpanStatusCode, ValueType, type Context } from '@opentelemetry/api';
27
+
28
+ type ValuesOf<T> = T extends Record<string, infer U> ? U : never;
29
+
30
+ type AttributeNames = ValuesOf<typeof Attributes>;
31
+
32
+ type AllowedVendorMetricAttributeNames = (typeof VendorAttributes)['ATTR_JSONRPC_METHOD' | 'ATTR_JSONRPC_SERVICE'];
33
+
34
+ /**
35
+ * This is a set of attributes that could lead to high cardinality in the metrics.
36
+ * If you find yourself wanting to capture this data in a metric consider if it makes sense to capture
37
+ * as the metric value instead of an attribute or consider logging instead.
38
+ *
39
+ * Think twice before removing an attribute from this list.
40
+ */
41
+ type BannedMetricAttributeNames = (typeof Attributes)[
42
+ | 'BLOCK_NUMBER'
43
+ | 'BLOCK_ARCHIVE'
44
+ | 'SLOT_NUMBER'
45
+ | 'BLOCK_PARENT'
46
+ | 'BLOCK_CANDIDATE_TXS_COUNT'
47
+ | 'BLOCK_TXS_COUNT'
48
+ | 'BLOCK_SIZE'
49
+ | 'EPOCH_SIZE'
50
+ | 'EPOCH_NUMBER'
51
+ | 'TX_HASH'
52
+ | 'PROVING_JOB_ID'
53
+ | 'P2P_ID'
54
+ | 'TARGET_ADDRESS'
55
+ | 'MANA_USED'
56
+ | 'TOTAL_INSTRUCTIONS'];
57
+
58
+ /** Global registry of attributes */
59
+ export type AttributesType = Partial<Record<AttributeNames, AttributeValue>>;
60
+
61
+ export type AllowedAttributeNames =
62
+ | Exclude<AttributeNames, BannedMetricAttributeNames>
63
+ | AllowedVendorMetricAttributeNames;
64
+
65
+ /** Subset of attributes allowed to be added to metrics */
66
+ export type MetricAttributesType = Partial<Record<AllowedAttributeNames, AttributeValue>>;
67
+
68
+ /** Re-export MetricDefinition for convenience */
69
+ export type { MetricDefinition } from './metrics.js';
70
+
71
+ export type Gauge = OtelGauge<MetricAttributesType>;
72
+ export type Histogram = OtelHistogram<MetricAttributesType>;
73
+ export type UpDownCounter = OtelUpDownCounter<MetricAttributesType>;
74
+ export type ObservableGauge = OtelObservableGauge<MetricAttributesType>;
75
+ export type ObservableUpDownCounter = OtelObservableUpDownCounter<MetricAttributesType>;
76
+ export type ObservableResult = OtelObservableResult<MetricAttributesType>;
77
+ export type BatchObservableResult = OtelBatchObservableResult<MetricAttributesType>;
78
+
79
+ export type { Tracer };
80
+
81
+ // INTERNAL NOTE: this interface is the same as opentelemetry's Meter, but with proper types
82
+ /**
83
+ * A meter that provides instruments for recording metrics.
84
+ */
85
+ export interface Meter {
86
+ /**
87
+ * Creates a new gauge instrument. A gauge is a metric that represents a single numerical value that can arbitrarily go up and down.
88
+ * @param metric - The metric definition
89
+ */
90
+ createGauge(metric: MetricDefinition): Gauge;
91
+
92
+ /**
93
+ * Creates a new observable gauge instrument. A gauge is a metric that represents a single numerical value that can arbitrarily go up and down.
94
+ * @param metric - The metric definition
95
+ */
96
+ createObservableGauge(metric: MetricDefinition): ObservableGauge;
97
+
98
+ addBatchObservableCallback(
99
+ callback: BatchObservableCallback<AttributesType>,
100
+ observables: Observable<AttributesType>[],
101
+ ): void;
102
+
103
+ removeBatchObservableCallback(
104
+ callback: BatchObservableCallback<AttributesType>,
105
+ observables: Observable<AttributesType>[],
106
+ ): void;
107
+
108
+ /**
109
+ * Creates a new histogram instrument. A histogram is a metric that samples observations (usually things like request durations or response sizes) and counts them in configurable buckets.
110
+ * @param metric - The metric definition
111
+ * @param extraOptions - Optional extra options (e.g., advice for bucket boundaries)
112
+ */
113
+ createHistogram(metric: MetricDefinition, extraOptions?: Partial<MetricOptions>): Histogram;
114
+
115
+ /**
116
+ * Creates a new counter instrument. A counter can go up or down with a delta from the previous value.
117
+ * @param metric - The metric definition
118
+ */
119
+ createUpDownCounter(metric: MetricDefinition): UpDownCounter;
120
+
121
+ /**
122
+ * Creates a new observable up/down counter instrument.
123
+ * @param metric - The metric definition
124
+ */
125
+ createObservableUpDownCounter(metric: MetricDefinition): ObservableUpDownCounter;
126
+ }
127
+
128
+ /**
129
+ * A telemetry client that provides meters for recording metrics.
130
+ */
131
+ export interface TelemetryClient {
132
+ /**
133
+ * Whether the client is enabled and reporting metrics.
134
+ **/
135
+ isEnabled(): boolean;
136
+ /**
137
+ * Creates a new meter
138
+ * @param name - The name of the meter.
139
+ */
140
+ getMeter(name: string): Meter;
141
+
142
+ /**
143
+ * Creates a new tracer
144
+ * @param name - The name of the tracer.
145
+ */
146
+ getTracer(name: string): Tracer;
147
+
148
+ /**
149
+ * Stops the telemetry client.
150
+ */
151
+ stop(): Promise<void>;
152
+
153
+ /**
154
+ * Flushes the telemetry client.
155
+ */
156
+ flush(): Promise<void>;
157
+
158
+ /**
159
+ * Updates what telemetry is exported to the public collector
160
+ */
161
+ setExportedPublicTelemetry(prefixes: string[]): void;
162
+
163
+ /**
164
+ * Updates the roles that would share telemetry (if enabled)
165
+ */
166
+ setPublicTelemetryCollectFrom(roles: string[]): void;
167
+
168
+ /**
169
+ * Get current trace context as an opaque string for propagation.
170
+ * Returns the W3C traceparent header value if a trace is active, undefined otherwise.
171
+ */
172
+ getTraceContext(): string | undefined;
173
+
174
+ /**
175
+ * Recreates a context propagated by a remote system
176
+ */
177
+ extractPropagatedContext(traceContext: string): Context | undefined;
178
+ }
179
+
180
+ /** Objects that adhere to this interface can use @trackSpan */
181
+ export interface Traceable {
182
+ tracer: Tracer;
183
+ }
184
+
185
+ type SpanDecorator<T extends Traceable, F extends (...args: any[]) => any> = (
186
+ originalMethod: F,
187
+ context: ClassMethodDecoratorContext<T>,
188
+ ) => F;
189
+
190
+ /**
191
+ * Starts a new span whenever the decorated method is called.
192
+ * @param spanName - The name of the span to create. Can be a string or a function that returns a string.
193
+ * @param attributes - Initial attributes to set on the span. If a function is provided, it will be called with the arguments of the method.
194
+ * @param extraAttributes - Extra attributes to set on the span after the method is called. Will be called with the return value of the method. Note: if the function throws then this will not be called.
195
+ * @returns A decorator that wraps the method in a span.
196
+ *
197
+ * @privateRemarks
198
+ * This code looks complex but it's not that difficult:
199
+ * - decorators are functions that _replace_ a method with a different implementation
200
+ * - normal decorators can't take function arguments, but if we write a function that returns a decorator, we can pass arguments to that function
201
+ *
202
+ * The trackSpan function takes a span's name and some attributes and builds a decorator that wraps a method in a span with the given name and props
203
+ * The decorator can currently only be applied to methods on classes that have a `tracer` property. The compiler will enforce this.
204
+ */
205
+ export function trackSpan<T extends Traceable, F extends (...args: any[]) => any>(
206
+ spanName: string | ((this: T, ...args: Parameters<F>) => string),
207
+ attributes?: AttributesType | ((this: T, ...args: Parameters<F>) => Promise<AttributesType> | AttributesType),
208
+ extraAttributes?: (this: T, returnValue: Awaited<ReturnType<F>>) => AttributesType,
209
+ ): SpanDecorator<T, F> {
210
+ // the return value of trackSpan is a decorator
211
+ return (originalMethod: F, _context: ClassMethodDecoratorContext<T>) => {
212
+ // the return value of the decorator replaces the original method
213
+ // in this wrapper method we start a span, call the original method, and then end the span
214
+ return async function replacementMethod(this: T, ...args: Parameters<F>): Promise<Awaited<ReturnType<F>>> {
215
+ const name = typeof spanName === 'function' ? spanName.call(this, ...args) : spanName;
216
+ const currentAttrs = typeof attributes === 'function' ? await attributes.call(this, ...args) : attributes;
217
+
218
+ // run originalMethod wrapped in an active span
219
+ // "active" means the span will be alive for the duration of the function execution
220
+ // and if any other spans are started during the execution of originalMethod, they will be children of this span
221
+ // behind the scenes this uses AsyncLocalStorage https://nodejs.org/dist/latest-v22.x/docs/api/async_context.html
222
+ return this.tracer.startActiveSpan(
223
+ name,
224
+ {
225
+ attributes: currentAttrs,
226
+ },
227
+ async (span: Span) => {
228
+ try {
229
+ const res = await originalMethod.call(this, ...args);
230
+ const extraAttrs = extraAttributes?.call(this, res);
231
+ span.setAttributes(extraAttrs ?? {});
232
+ span.setStatus({
233
+ code: SpanStatusCode.OK,
234
+ });
235
+ return res;
236
+ } catch (err) {
237
+ span.setStatus({
238
+ code: SpanStatusCode.ERROR,
239
+ message: String(err),
240
+ });
241
+
242
+ if (typeof err === 'string' || (err && err instanceof Error)) {
243
+ span.recordException(err);
244
+ }
245
+
246
+ throw err;
247
+ } finally {
248
+ span.end();
249
+ }
250
+ },
251
+ );
252
+ } as F;
253
+ };
254
+ }
255
+
256
+ /**
257
+ * Runs an event callback in a span. The span is started immediately and completes once the callback finishes running.
258
+ * The span will have two events added: 'callbackStart' and 'callbackEnd' to mark the start and end of the callback.
259
+ *
260
+ * @param tracer - The tracer instance to use
261
+ * @param spanName - The name of the span to create
262
+ * @param attributes - Initial attributes to set on the span
263
+ * @param callback - The callback to wrap in a span
264
+ *
265
+ * @returns - A new function that wraps the callback in a span
266
+ */
267
+ export function wrapCallbackInSpan<F extends (...args: any[]) => any>(
268
+ tracer: Tracer,
269
+ spanName: string,
270
+ attributes: AttributesType,
271
+ callback: F,
272
+ ): F {
273
+ const span = tracer.startSpan(spanName, { attributes });
274
+ return (async (...args: Parameters<F>) => {
275
+ try {
276
+ span.addEvent('callbackStart');
277
+ const res = await callback(...args);
278
+ return res;
279
+ } catch (err) {
280
+ span.setStatus({
281
+ code: SpanStatusCode.ERROR,
282
+ message: String(err),
283
+ });
284
+ throw err;
285
+ } finally {
286
+ span.addEvent('callbackEnd');
287
+ span.end();
288
+ }
289
+ }) as F;
290
+ }
291
+
292
+ export function runInSpan<A extends any[], R>(
293
+ tracer: Tracer | string,
294
+ spanName: string,
295
+ callback: (span: Span, ...args: A) => Promise<R>,
296
+ ): (...args: A) => Promise<R> {
297
+ return (...args: A): Promise<R> => {
298
+ const actualTracer = typeof tracer === 'string' ? getTelemetryClient().getTracer(tracer) : tracer;
299
+ return actualTracer.startActiveSpan(spanName, async (span: Span): Promise<R> => {
300
+ try {
301
+ const res = await callback(span, ...args);
302
+ span.setStatus({
303
+ code: SpanStatusCode.OK,
304
+ });
305
+
306
+ return res;
307
+ } catch (err) {
308
+ span.setStatus({
309
+ code: SpanStatusCode.ERROR,
310
+ message: String(err),
311
+ });
312
+ if (typeof err === 'string' || (err && err instanceof Error)) {
313
+ span.recordException(err);
314
+ }
315
+ throw err;
316
+ } finally {
317
+ span.end();
318
+ }
319
+ });
320
+ };
321
+ }
322
+
323
+ /**
324
+ * Execute a callback within a span immediately (for one-off traced calls).
325
+ * Unlike runInSpan which returns a reusable function, this executes right away.
326
+ */
327
+ export function execInSpan<R>(
328
+ tracer: Tracer | string,
329
+ spanName: string,
330
+ callback: (span: Span) => Promise<R>,
331
+ ): Promise<R> {
332
+ const actualTracer = typeof tracer === 'string' ? getTelemetryClient().getTracer(tracer) : tracer;
333
+ return actualTracer.startActiveSpan(spanName, async (span: Span): Promise<R> => {
334
+ try {
335
+ const res = await callback(span);
336
+ span.setStatus({ code: SpanStatusCode.OK });
337
+ return res;
338
+ } catch (err) {
339
+ span.setStatus({ code: SpanStatusCode.ERROR, message: String(err) });
340
+ if (typeof err === 'string' || (err && err instanceof Error)) {
341
+ span.recordException(err);
342
+ }
343
+ throw err;
344
+ } finally {
345
+ span.end();
346
+ }
347
+ });
348
+ }
@@ -0,0 +1,6 @@
1
+ // See https://opentelemetry.io/docs/specs/semconv/rpc/json-rpc/
2
+ export const ATTR_JSONRPC_METHOD = 'rpc.method';
3
+ export const ATTR_JSONRPC_SERVICE = 'rpc.service';
4
+ export const ATTR_JSONRPC_REQUEST_ID = 'rpc.jsonrpc.request_id';
5
+ export const ATTR_JSONRPC_ERROR_CODE = 'rpc.jsonrpc.error_code';
6
+ export const ATTR_JSONRPC_ERROR_MSG = 'rpc.jsonrpc.error_message';
@@ -0,0 +1,279 @@
1
+ /*
2
+ * Adapted from open-telemetry/opentelemetry-js-contrib
3
+ * All changes are prefixed with [aztec] to make them easy to identify
4
+ *
5
+ * Copyright The OpenTelemetry Authors
6
+ *
7
+ * Licensed under the Apache License, Version 2.0 (the "License");
8
+ * you may not use this file except in compliance with the License.
9
+ * You may obtain a copy of the License at
10
+ *
11
+ * https://www.apache.org/licenses/LICENSE-2.0
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+ import { type Logger, SeverityNumber, logs } from '@opentelemetry/api-logs';
20
+ import { millisToHrTime } from '@opentelemetry/core';
21
+ import { Writable } from 'stream';
22
+
23
+ import { registerOtelLoggerProvider } from '../otel_logger_provider.js';
24
+ import { getOtelResource } from '../otel_resource.js';
25
+
26
+ // This block is a copy (modulo code style and TypeScript types) of the Pino
27
+ // code that defines log level value and names. This file is part of
28
+ // *instrumenting* Pino, so we want to avoid a dependency on the library.
29
+ const DEFAULT_LEVELS = {
30
+ trace: 10,
31
+ debug: 20,
32
+ info: 30,
33
+ warn: 40,
34
+ error: 50,
35
+ fatal: 60,
36
+ };
37
+
38
+ const OTEL_SEV_NUM_FROM_PINO_LEVEL: { [level: number]: SeverityNumber } = {
39
+ [DEFAULT_LEVELS.trace]: SeverityNumber.TRACE,
40
+ [DEFAULT_LEVELS.debug]: SeverityNumber.DEBUG,
41
+ [DEFAULT_LEVELS.info]: SeverityNumber.INFO,
42
+ [DEFAULT_LEVELS.warn]: SeverityNumber.WARN,
43
+ [DEFAULT_LEVELS.error]: SeverityNumber.ERROR,
44
+ [DEFAULT_LEVELS.fatal]: SeverityNumber.FATAL,
45
+ };
46
+
47
+ const EXTRA_SEV_NUMS = [
48
+ SeverityNumber.TRACE2,
49
+ SeverityNumber.TRACE3,
50
+ SeverityNumber.TRACE4,
51
+ SeverityNumber.DEBUG2,
52
+ SeverityNumber.DEBUG3,
53
+ SeverityNumber.DEBUG4,
54
+ SeverityNumber.INFO2,
55
+ SeverityNumber.INFO3,
56
+ SeverityNumber.INFO4,
57
+ SeverityNumber.WARN2,
58
+ SeverityNumber.WARN3,
59
+ SeverityNumber.WARN4,
60
+ SeverityNumber.ERROR2,
61
+ SeverityNumber.ERROR3,
62
+ SeverityNumber.ERROR4,
63
+ SeverityNumber.FATAL2,
64
+ SeverityNumber.FATAL3,
65
+ SeverityNumber.FATAL4,
66
+ ];
67
+
68
+ function severityNumberFromPinoLevel(lvl: number) {
69
+ // Fast common case: one of the known levels
70
+ const sev = OTEL_SEV_NUM_FROM_PINO_LEVEL[lvl];
71
+ if (sev !== undefined) {
72
+ return sev;
73
+ }
74
+
75
+ // Otherwise, scale the Pino level range -- 10 (trace) to 70 (fatal+10)
76
+ // -- onto the extra OTel severity numbers (TRACE2, TRACE3, ..., FATAL4).
77
+ // Values below trace (10) map to SeverityNumber.TRACE2, which may be
78
+ // considered a bit weird, but it means the unnumbered levels are always
79
+ // just for exactly matching values.
80
+ const relativeLevelWeight = (lvl - 10) / (70 - 10);
81
+ const otelSevIdx = Math.floor(relativeLevelWeight * EXTRA_SEV_NUMS.length);
82
+ const cappedOTelIdx = Math.min(EXTRA_SEV_NUMS.length - 1, Math.max(0, otelSevIdx));
83
+ const otelSevValue = EXTRA_SEV_NUMS[cappedOTelIdx];
84
+ return otelSevValue;
85
+ }
86
+
87
+ // [aztec] Custom function to map Aztec logging levels to OpenTelemetry severity numbers
88
+ function severityNumberFromAztecPinoLevel(lvl: number) {
89
+ return (
90
+ OTEL_SEV_NUM_FROM_PINO_LEVEL[lvl] ??
91
+ /* verbose */ (lvl === 25 ? SeverityNumber.DEBUG3 : undefined) ??
92
+ severityNumberFromPinoLevel(lvl)
93
+ );
94
+ }
95
+
96
+ /**
97
+ * Return a function that knows how to convert the "time" field value on a
98
+ * Pino log record to an OTel LogRecord timestamp value.
99
+ *
100
+ * How to convert the serialized "time" on a Pino log record
101
+ * depends on the Logger's `Symbol(pino.time)` prop, configurable
102
+ * via https://getpino.io/#/docs/api?id=timestamp-boolean-function
103
+ *
104
+ * For example:
105
+ * const logger = pino({timestamp: pino.stdTimeFunctions.isoTime})
106
+ * results in log record entries of the form:
107
+ * ,"time":"2024-05-17T22:03:25.969Z"
108
+ * `otelTimestampFromTime` will be given the value of the "time" field:
109
+ * "2024-05-17T22:03:25.969Z"
110
+ * which should be parsed to a number of milliseconds since the epoch.
111
+ */
112
+ export function getTimeConverter(pinoLogger: any, pinoMod: any) {
113
+ const stdTimeFns = pinoMod.stdTimeFunctions;
114
+ const loggerTimeFn = pinoLogger[pinoMod.symbols.timeSym];
115
+ if (loggerTimeFn === stdTimeFns.epochTime) {
116
+ return (time: number) => time;
117
+ } else if (loggerTimeFn === stdTimeFns.unixTime) {
118
+ return (time: number) => time * 1e3;
119
+ } else if (loggerTimeFn === stdTimeFns.isoTime) {
120
+ return (time: string) => new Date(time).getTime();
121
+ } else if (loggerTimeFn === stdTimeFns.nullTime) {
122
+ return () => Date.now();
123
+ } else {
124
+ // The logger has a custom time function. Don't guess.
125
+ return () => NaN;
126
+ }
127
+ }
128
+
129
+ interface OTelPinoStreamOptions {
130
+ messageKey?: string;
131
+ levels: any; // Pino.LevelMapping
132
+ otelTimestampFromTime?: (time: any) => number;
133
+ }
134
+
135
+ /**
136
+ * A Pino stream for sending records to the OpenTelemetry Logs API.
137
+ *
138
+ * - This stream emits an 'unknown' event on an unprocessable pino record.
139
+ * The event arguments are: `logLine: string`, `err: string | Error`.
140
+ */
141
+ export class OTelPinoStream extends Writable {
142
+ private _otelLogger: Logger;
143
+ private _messageKey: string;
144
+ private _levels;
145
+ private _otelTimestampFromTime;
146
+
147
+ constructor(options: OTelPinoStreamOptions) {
148
+ super();
149
+
150
+ // Note: A PINO_CONFIG event was added to pino (2024-04-04) to send config
151
+ // to transports. Eventually OTelPinoStream might be able to use this
152
+ // for auto-configuration in newer pino versions. The event currently does
153
+ // not include the `timeSym` value that is needed here, however.
154
+ this._messageKey = options.messageKey ?? 'msg';
155
+ this._levels = options.levels;
156
+
157
+ // [aztec] The following will break if we set up a custom time function in our logger
158
+ this._otelTimestampFromTime = options.otelTimestampFromTime ?? ((time: number) => time);
159
+
160
+ // Cannot use `instrumentation.logger` until have delegating LoggerProvider:
161
+ // https://github.com/open-telemetry/opentelemetry-js/issues/4399
162
+ // [aztec] Use the name of this package
163
+ this._otelLogger = logs.getLogger('@aztec-labs/telemetry-client/otel-pino-stream', '0.1.0');
164
+ }
165
+
166
+ override _write(s: string, _encoding: string, callback: Function) {
167
+ try {
168
+ /* istanbul ignore if */
169
+ if (!s) {
170
+ return;
171
+ }
172
+
173
+ // Parse, and handle edge cases similar to how `pino-abstract-transport` does:
174
+ // https://github.com/pinojs/pino-abstract-transport/blob/v1.2.0/index.js#L28-L45
175
+ // - Emitting an 'unknown' event on parse error mimicks pino-abstract-transport.
176
+ let recObj;
177
+ try {
178
+ recObj = JSON.parse(s);
179
+ } catch (parseErr) {
180
+ // Invalid JSON suggests a bug in Pino, or a logger configuration bug
181
+ // (a bogus `options.timestamp` or serializer).
182
+ this.emit('unknown', s.toString(), parseErr);
183
+ callback();
184
+ return;
185
+ }
186
+ /* istanbul ignore if */
187
+ if (recObj === null) {
188
+ this.emit('unknown', s.toString(), 'Null value ignored');
189
+ callback();
190
+ return;
191
+ }
192
+ /* istanbul ignore if */
193
+ if (typeof recObj !== 'object') {
194
+ recObj = {
195
+ data: recObj,
196
+ };
197
+ }
198
+
199
+ const {
200
+ time,
201
+ [this._messageKey]: body,
202
+ level, // eslint-disable-line @typescript-eslint/no-unused-vars
203
+
204
+ // The typical Pino `hostname` and `pid` fields are removed because they
205
+ // are redundant with the OpenTelemetry `host.name` and `process.pid`
206
+ // Resource attributes, respectively. This code cannot change the
207
+ // LoggerProvider's `resource`, so getting the OpenTelemetry equivalents
208
+ // depends on the user using the OpenTelemetry HostDetector and
209
+ // ProcessDetector.
210
+ // https://getpino.io/#/docs/api?id=opt-base
211
+ hostname, // eslint-disable-line @typescript-eslint/no-unused-vars
212
+ pid, // eslint-disable-line @typescript-eslint/no-unused-vars
213
+
214
+ // The `trace_id` et al fields that may have been added by the
215
+ // "log correlation" feature are stripped, because they are redundant.
216
+ // trace_id, // eslint-disable-line @typescript-eslint/no-unused-vars
217
+ // span_id, // eslint-disable-line @typescript-eslint/no-unused-vars
218
+ // trace_flags, // eslint-disable-line @typescript-eslint/no-unused-vars
219
+
220
+ // [aztec] They are not redundant, we depend on them for correlation.
221
+ // The instrumentation package seems to be adding these fields via a custom hook.
222
+ // We push them from the logger module in foundation, so we don't want to clear them here.
223
+
224
+ ...attributes
225
+ } = recObj;
226
+
227
+ let timestamp = this._otelTimestampFromTime(time);
228
+ if (isNaN(timestamp)) {
229
+ attributes['time'] = time; // save the unexpected "time" field to attributes
230
+ timestamp = Date.now();
231
+ }
232
+
233
+ // This avoids a possible subtle bug when a Pino logger uses
234
+ // `time: pino.stdTimeFunctions.unixTime` and logs in the first half-second
235
+ // since process start. The rounding involved results in:
236
+ // timestamp < performance.timeOrigin
237
+ // If that is passed to Logger.emit() it will be misinterpreted by
238
+ // `timeInputToHrTime` as a `performance.now()` value.
239
+ const timestampHrTime = millisToHrTime(timestamp);
240
+
241
+ // Prefer using `stream.lastLevel`, because `recObj.level` can be customized
242
+ // to anything via `formatters.level`
243
+ // (https://getpino.io/#/docs/api?id=formatters-object).
244
+ // const lastLevel = (this as any).lastLevel;
245
+
246
+ // [aztec] We do not prefer stream.lastLevel since it's undefined here, as we are running
247
+ // on a worker thread, so we use recObj.level because we know that we won't customize it.
248
+ const lastLevel = recObj.level;
249
+
250
+ const otelRec = {
251
+ timestamp: timestampHrTime,
252
+ observedTimestamp: timestampHrTime,
253
+ severityNumber: severityNumberFromAztecPinoLevel(lastLevel),
254
+ severityText: this._levels.labels[lastLevel],
255
+ body,
256
+ attributes,
257
+ };
258
+
259
+ this._otelLogger.emit(otelRec);
260
+ } catch (err) {
261
+ // [aztec] Log errors to stderr
262
+ // eslint-disable-next-line no-console
263
+ console.error(`Error in OTelPinoStream: ${err}`);
264
+ }
265
+ callback();
266
+ }
267
+ }
268
+
269
+ // [aztec] Default export that loads the resource information and creates a new otel pino stream.
270
+ // Invoked by pino when creating a transport in a worker thread out of this stream.
271
+ // Note that the original open-telemetry/opentelemetry-js-contrib was set up to run on the main
272
+ // nodejs loop, as opposed to in a worker as pino recommends.
273
+ export default function (options: OTelPinoStreamOptions): OTelPinoStream {
274
+ const url = process.env.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT;
275
+ const resource = getOtelResource();
276
+ // We re-register here because this runs on a worker thread
277
+ registerOtelLoggerProvider(resource, url ? new URL(url) : undefined);
278
+ return new OTelPinoStream(options);
279
+ }
@@ -0,0 +1,35 @@
1
+ import type { TelemetryClient, Tracer } from './telemetry.js';
2
+
3
+ /**
4
+ * A minimal class that enables recording metrics with a telemetry client.
5
+ * This base class enables tracing
6
+ *
7
+ * In other words:
8
+ * Enables the ability to call `@trackSpan` on methods.
9
+ *
10
+ * Example:
11
+ *
12
+ * ```
13
+ * import {Attributes, type TelemetryClient, WithTracer, trackSpan } from '@aztec-labs/telemetry-client';
14
+ *
15
+ * class MyClass extends WithTracer {
16
+ * // Constructor is required to be passed the TelemetryClient implementation.
17
+ * constructor(client: TelemetryClient) {
18
+ * super(client, 'MyClass');
19
+ * }
20
+ *
21
+ * @trackSpan('MyClass.myMethod', (arg: string) => ({
22
+ * [Attributes.ARG]: arg,
23
+ * }))
24
+ * public myMethod(arg: string) {
25
+ * // ...
26
+ * }
27
+ * }
28
+ * ```
29
+ */
30
+ export class WithTracer {
31
+ public readonly tracer: Tracer;
32
+ constructor(client: TelemetryClient, name: string) {
33
+ this.tracer = client.getTracer(name);
34
+ }
35
+ }