@saplings/observability 0.0.0-stage → 0.1.0
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.
- package/CHANGELOG.md +7 -0
- package/LICENSE +21 -0
- package/README.md +93 -2
- package/dist/index.d.ts +11 -0
- package/dist/index.js +30 -0
- package/dist/index.js.map +1 -0
- package/dist/logger.d.ts +21 -0
- package/dist/logger.js +97 -0
- package/dist/logger.js.map +1 -0
- package/dist/node-diagnostics.d.ts +13 -0
- package/dist/node-diagnostics.js +29 -0
- package/dist/node-diagnostics.js.map +1 -0
- package/dist/request-metrics.d.ts +12 -0
- package/dist/request-metrics.js +20 -0
- package/dist/request-metrics.js.map +1 -0
- package/package.json +41 -3
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
# @saplings/observability
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- d8be144: Add a shared Node.js observability package for structured logs, OpenTelemetry traces and metrics, and process and request diagnostics. The SDK and quality diagnostics use the shared implementations through their existing exports.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Sapling Unified SDK contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,94 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @saplings/observability
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Reusable backend observability for Node.js services. Write structured JSON logs, correlate them with OpenTelemetry spans, record metrics with an OpenTelemetry meter, and measure the health of a Node.js process.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
Use Node.js 22 or later. This package ships ESM and TypeScript declarations.
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @saplings/observability
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Instrument application work
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { createObservability } from '@saplings/observability';
|
|
17
|
+
|
|
18
|
+
const telemetry = createObservability({ serviceName: 'orders' });
|
|
19
|
+
const processed = telemetry.meter.createCounter('orders.processed');
|
|
20
|
+
|
|
21
|
+
await telemetry.withSpan('orders.process', async (span) => {
|
|
22
|
+
span.setAttribute('orders.source', 'batch');
|
|
23
|
+
processed.add(1, { source: 'batch' });
|
|
24
|
+
await telemetry.log({
|
|
25
|
+
level: 'info',
|
|
26
|
+
event: 'orders.processed',
|
|
27
|
+
fields: { source: 'batch' },
|
|
28
|
+
});
|
|
29
|
+
});
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Logs go to stdout by default and include `trace_id` and `span_id` when a valid span is active. The default level is `info`. Pass `write` to use another sink or `redactKeys` to add service-specific sensitive keys. The logger redacts common credential fields recursively, including headers such as `Authorization` and `Cookie`. Pass only approved structured fields and keep sensitive values out of event names and trace attributes.
|
|
33
|
+
|
|
34
|
+
## Export traces and metrics
|
|
35
|
+
|
|
36
|
+
Initialize an OpenTelemetry provider in the host service before loading the application. Use Node.js 22.15 or later for this OpenTelemetry SDK setup. Install the Node SDK and HTTP instrumentation.
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
npm install @opentelemetry/api@^1.10.0 @opentelemetry/sdk-node@0.301.2 @opentelemetry/instrumentation-http@0.301.2
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Save this as `instrumentation.mjs`.
|
|
43
|
+
|
|
44
|
+
```js
|
|
45
|
+
import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';
|
|
46
|
+
import { NodeSDK } from '@opentelemetry/sdk-node';
|
|
47
|
+
|
|
48
|
+
export const sdk = new NodeSDK({ instrumentations: [new HttpInstrumentation()] });
|
|
49
|
+
sdk.start();
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Point the service at an OpenTelemetry Collector and preload the instrumentation.
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
OTEL_SERVICE_NAME=orders \
|
|
56
|
+
OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4318 \
|
|
57
|
+
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf \
|
|
58
|
+
OTEL_TRACES_EXPORTER=otlp \
|
|
59
|
+
OTEL_METRICS_EXPORTER=otlp \
|
|
60
|
+
OTEL_LOGS_EXPORTER=none \
|
|
61
|
+
OTEL_SEMCONV_STABILITY_OPT_IN=http \
|
|
62
|
+
node --import ./instrumentation.mjs server.mjs
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Configure the collector to receive OTLP over HTTP. The HTTP instrumentation creates request spans and propagates trace context. Use stable operation names and bounded metric attributes such as a route template or operation type. Flush pending exports with `await sdk.shutdown()` during the application's shutdown sequence. Collect JSON stdout through your platform's log pipeline. Until a provider is registered, OpenTelemetry spans and metrics use its no-op defaults.
|
|
66
|
+
|
|
67
|
+
## API
|
|
68
|
+
|
|
69
|
+
| Entry point | Use |
|
|
70
|
+
| --- | --- |
|
|
71
|
+
| `createLogger(options)` | Returns an async `log(event)` function when you need structured logs alone. |
|
|
72
|
+
| `createObservability(options)` | Returns `log`, `tracer`, `meter`, and `withSpan`. |
|
|
73
|
+
| `withSpan(name, work, options?)` | Runs an async or synchronous operation in an active span, closes it on completion, and propagates the original error. |
|
|
74
|
+
| `createNodeDiagnostics()` | Starts collection of memory, CPU usage, uptime, and event-loop delay. Call `snapshot()` to sample and `close()` to stop. |
|
|
75
|
+
| `new RequestMetrics()` | Keeps local request totals, 5xx totals, mean duration in milliseconds, and availability. Use `observe(status, durationMs)` and `snapshot()`. |
|
|
76
|
+
|
|
77
|
+
For Saplings SDK logging, pass the telemetry object as `providers.telemetry` when you call `createSapling`. Use `createNodeDiagnostics` and `RequestMetrics` for health snapshots or tests. Aggregating metrics across processes requires the configured OpenTelemetry provider and collector.
|
|
78
|
+
|
|
79
|
+
## Read a process snapshot
|
|
80
|
+
|
|
81
|
+
```ts
|
|
82
|
+
import { createNodeDiagnostics, RequestMetrics } from '@saplings/observability';
|
|
83
|
+
|
|
84
|
+
const diagnostics = createNodeDiagnostics();
|
|
85
|
+
const requests = new RequestMetrics();
|
|
86
|
+
|
|
87
|
+
try {
|
|
88
|
+
requests.observe(200, 15);
|
|
89
|
+
requests.observe(503, 25);
|
|
90
|
+
console.log({ process: diagnostics.snapshot(), requests: requests.snapshot() });
|
|
91
|
+
} finally {
|
|
92
|
+
diagnostics.close();
|
|
93
|
+
}
|
|
94
|
+
```
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type Span, type SpanOptions } from '@opentelemetry/api';
|
|
2
|
+
import { type LoggerOptions } from './logger.js';
|
|
3
|
+
export { createLogger, type LoggerOptions, type LogEvent, type LogLevel } from './logger.js';
|
|
4
|
+
export { createNodeDiagnostics } from './node-diagnostics.js';
|
|
5
|
+
export { RequestMetrics } from './request-metrics.js';
|
|
6
|
+
export declare function createObservability(options: LoggerOptions): {
|
|
7
|
+
log: ({ level, event, at, fields }: import("./logger.js").LogEvent) => Promise<void>;
|
|
8
|
+
tracer: import("@opentelemetry/api").Tracer;
|
|
9
|
+
meter: import("@opentelemetry/api").Meter;
|
|
10
|
+
withSpan<T>(name: string, work: (span: Span) => T | Promise<T>, options?: SpanOptions): Promise<T>;
|
|
11
|
+
};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { metrics, SpanStatusCode, trace } from '@opentelemetry/api';
|
|
2
|
+
import { createLogger } from './logger.js';
|
|
3
|
+
export { createLogger } from './logger.js';
|
|
4
|
+
export { createNodeDiagnostics } from './node-diagnostics.js';
|
|
5
|
+
export { RequestMetrics } from './request-metrics.js';
|
|
6
|
+
export function createObservability(options) {
|
|
7
|
+
const log = createLogger(options);
|
|
8
|
+
const tracer = trace.getTracer('@saplings/observability');
|
|
9
|
+
const meter = metrics.getMeter('@saplings/observability');
|
|
10
|
+
return {
|
|
11
|
+
log,
|
|
12
|
+
tracer,
|
|
13
|
+
meter,
|
|
14
|
+
withSpan(name, work, options = {}) {
|
|
15
|
+
return tracer.startActiveSpan(name, options, async (span) => {
|
|
16
|
+
try {
|
|
17
|
+
return await work(span);
|
|
18
|
+
}
|
|
19
|
+
catch (error) {
|
|
20
|
+
span.setStatus({ code: SpanStatusCode.ERROR });
|
|
21
|
+
throw error;
|
|
22
|
+
}
|
|
23
|
+
finally {
|
|
24
|
+
span.end();
|
|
25
|
+
}
|
|
26
|
+
});
|
|
27
|
+
},
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,cAAc,EAAE,KAAK,EAA+B,MAAM,oBAAoB,CAAC;AACjG,OAAO,EAAE,YAAY,EAAsB,MAAM,aAAa,CAAC;AAE/D,OAAO,EAAE,YAAY,EAAoD,MAAM,aAAa,CAAC;AAC7F,OAAO,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAC9D,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAEtD,MAAM,UAAU,mBAAmB,CAAC,OAAsB;IACxD,MAAM,GAAG,GAAG,YAAY,CAAC,OAAO,CAAC,CAAC;IAClC,MAAM,MAAM,GAAG,KAAK,CAAC,SAAS,CAAC,yBAAyB,CAAC,CAAC;IAC1D,MAAM,KAAK,GAAG,OAAO,CAAC,QAAQ,CAAC,yBAAyB,CAAC,CAAC;IAE1D,OAAO;QACL,GAAG;QACH,MAAM;QACN,KAAK;QACL,QAAQ,CAAI,IAAY,EAAE,IAAoC,EAAE,UAAuB,EAAE;YACvF,OAAO,MAAM,CAAC,eAAe,CAAC,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE;gBAC1D,IAAI,CAAC;oBACH,OAAO,MAAM,IAAI,CAAC,IAAI,CAAC,CAAC;gBAC1B,CAAC;gBAAC,OAAO,KAAK,EAAE,CAAC;oBACf,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,cAAc,CAAC,KAAK,EAAE,CAAC,CAAC;oBAC/C,MAAM,KAAK,CAAC;gBACd,CAAC;wBAAS,CAAC;oBACT,IAAI,CAAC,GAAG,EAAE,CAAC;gBACb,CAAC;YACH,CAAC,CAAC,CAAC;QACL,CAAC;KACF,CAAC;AACJ,CAAC"}
|
package/dist/logger.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
declare const priorities: {
|
|
2
|
+
debug: number;
|
|
3
|
+
info: number;
|
|
4
|
+
warn: number;
|
|
5
|
+
error: number;
|
|
6
|
+
};
|
|
7
|
+
export type LogLevel = keyof typeof priorities;
|
|
8
|
+
export interface LogEvent {
|
|
9
|
+
level: LogLevel;
|
|
10
|
+
event: string;
|
|
11
|
+
at?: string;
|
|
12
|
+
fields?: Record<string, unknown>;
|
|
13
|
+
}
|
|
14
|
+
export interface LoggerOptions {
|
|
15
|
+
serviceName: string;
|
|
16
|
+
minLevel?: LogLevel;
|
|
17
|
+
redactKeys?: readonly string[];
|
|
18
|
+
write?: (line: string) => void | Promise<void>;
|
|
19
|
+
}
|
|
20
|
+
export declare function createLogger({ serviceName, minLevel, redactKeys, write, }: LoggerOptions): ({ level, event, at, fields }: LogEvent) => Promise<void>;
|
|
21
|
+
export {};
|
package/dist/logger.js
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { context, isSpanContextValid, trace } from '@opentelemetry/api';
|
|
2
|
+
import { stdout } from 'node:process';
|
|
3
|
+
const priorities = { debug: 10, info: 20, warn: 30, error: 40 };
|
|
4
|
+
const credentialKeys = [
|
|
5
|
+
'authorization',
|
|
6
|
+
'proxy-authorization',
|
|
7
|
+
'cookie',
|
|
8
|
+
'set-cookie',
|
|
9
|
+
'password',
|
|
10
|
+
'passwordHash',
|
|
11
|
+
'passphrase',
|
|
12
|
+
'secret',
|
|
13
|
+
'clientSecret',
|
|
14
|
+
'token',
|
|
15
|
+
'accessToken',
|
|
16
|
+
'refreshToken',
|
|
17
|
+
'idToken',
|
|
18
|
+
'sessionToken',
|
|
19
|
+
'apiKey',
|
|
20
|
+
'x-api-key',
|
|
21
|
+
'privateKey',
|
|
22
|
+
'otp',
|
|
23
|
+
];
|
|
24
|
+
const normalizeKey = (key) => key.toLowerCase().replace(/[^a-z0-9]/g, '');
|
|
25
|
+
function sanitizeFields(fields, redact) {
|
|
26
|
+
let remaining = 200;
|
|
27
|
+
const ancestors = new WeakSet();
|
|
28
|
+
function copy(value, depth) {
|
|
29
|
+
if (remaining-- <= 0 || depth > 6)
|
|
30
|
+
return '[Truncated]';
|
|
31
|
+
if (typeof value === 'string')
|
|
32
|
+
return value.slice(0, 2048);
|
|
33
|
+
if (value === null || typeof value === 'number' || typeof value === 'boolean')
|
|
34
|
+
return value;
|
|
35
|
+
if (typeof value === 'bigint')
|
|
36
|
+
return String(value);
|
|
37
|
+
if (typeof value !== 'object')
|
|
38
|
+
return undefined;
|
|
39
|
+
if (ancestors.has(value))
|
|
40
|
+
return '[Circular]';
|
|
41
|
+
const isArray = Array.isArray(value);
|
|
42
|
+
const prototype = Object.getPrototypeOf(value);
|
|
43
|
+
if (!isArray && prototype !== Object.prototype && prototype !== null)
|
|
44
|
+
return '[Unsupported]';
|
|
45
|
+
ancestors.add(value);
|
|
46
|
+
const result = isArray ? [] : Object.create(null);
|
|
47
|
+
const keys = isArray
|
|
48
|
+
? Array.from({ length: Math.min(value.length, 50) }, (_, index) => String(index))
|
|
49
|
+
: Object.keys(value).slice(0, 50);
|
|
50
|
+
for (const key of keys) {
|
|
51
|
+
if (remaining <= 0)
|
|
52
|
+
break;
|
|
53
|
+
if (key.length > 128)
|
|
54
|
+
continue;
|
|
55
|
+
const property = Object.getOwnPropertyDescriptor(value, key);
|
|
56
|
+
if (property && 'value' in property) {
|
|
57
|
+
if (redact.has(normalizeKey(key))) {
|
|
58
|
+
remaining--;
|
|
59
|
+
result[key] = '[Redacted]';
|
|
60
|
+
}
|
|
61
|
+
else
|
|
62
|
+
result[key] = copy(property.value, depth + 1);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
ancestors.delete(value);
|
|
66
|
+
return result;
|
|
67
|
+
}
|
|
68
|
+
return copy(fields, 0);
|
|
69
|
+
}
|
|
70
|
+
export function createLogger({ serviceName, minLevel = 'info', redactKeys = [], write = (line) => {
|
|
71
|
+
stdout.write(line);
|
|
72
|
+
}, }) {
|
|
73
|
+
const service = serviceName.trim();
|
|
74
|
+
if (!service || service.length > 128)
|
|
75
|
+
throw new Error('Provide a service name of 1 to 128 characters');
|
|
76
|
+
const redact = new Set([...credentialKeys, ...redactKeys].map(normalizeKey));
|
|
77
|
+
return async function log({ level, event, at, fields }) {
|
|
78
|
+
if (!Object.hasOwn(priorities, level) || priorities[level] < priorities[minLevel])
|
|
79
|
+
return;
|
|
80
|
+
try {
|
|
81
|
+
const span = trace.getSpanContext(context.active());
|
|
82
|
+
const traceFields = span && isSpanContextValid(span) ? { trace_id: span.traceId, span_id: span.spanId } : {};
|
|
83
|
+
await write(JSON.stringify({
|
|
84
|
+
at: at ?? new Date().toISOString(),
|
|
85
|
+
level,
|
|
86
|
+
service,
|
|
87
|
+
event: event.slice(0, 128),
|
|
88
|
+
...traceFields,
|
|
89
|
+
...(fields && { fields: sanitizeFields(fields, redact) }),
|
|
90
|
+
}) + '\n');
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
// A failed sink or unserializable optional field must not fail application work.
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
//# sourceMappingURL=logger.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"logger.js","sourceRoot":"","sources":["../src/logger.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,kBAAkB,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AACxE,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAEtC,MAAM,UAAU,GAAG,EAAE,KAAK,EAAE,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC;AAChE,MAAM,cAAc,GAAG;IACrB,eAAe;IACf,qBAAqB;IACrB,QAAQ;IACR,YAAY;IACZ,UAAU;IACV,cAAc;IACd,YAAY;IACZ,QAAQ;IACR,cAAc;IACd,OAAO;IACP,aAAa;IACb,cAAc;IACd,SAAS;IACT,cAAc;IACd,QAAQ;IACR,WAAW;IACX,YAAY;IACZ,KAAK;CACN,CAAC;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P,iFAAiF;QACnF,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** Collect Node.js process metrics and event-loop delay. Close the collector when finished. */
|
|
2
|
+
export declare function createNodeDiagnostics(): {
|
|
3
|
+
snapshot(): {
|
|
4
|
+
eventLoopLagP95Ms: number;
|
|
5
|
+
eventLoopLagMaxMs: number;
|
|
6
|
+
heapUsedMb: number;
|
|
7
|
+
rssMb: number;
|
|
8
|
+
externalMb: number;
|
|
9
|
+
cpuPercent: number;
|
|
10
|
+
uptimeSeconds: number;
|
|
11
|
+
};
|
|
12
|
+
close(): void;
|
|
13
|
+
};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { performance, monitorEventLoopDelay } from 'node:perf_hooks';
|
|
2
|
+
import { memoryUsage, cpuUsage } from 'node:process';
|
|
3
|
+
/** Collect Node.js process metrics and event-loop delay. Close the collector when finished. */
|
|
4
|
+
export function createNodeDiagnostics() {
|
|
5
|
+
const histogram = monitorEventLoopDelay({ resolution: 20 });
|
|
6
|
+
histogram.enable();
|
|
7
|
+
let previousCPU = cpuUsage(), previousTime = performance.now();
|
|
8
|
+
return {
|
|
9
|
+
snapshot() {
|
|
10
|
+
const now = performance.now(), cpu = cpuUsage(previousCPU), delta = now - previousTime;
|
|
11
|
+
previousTime = now;
|
|
12
|
+
previousCPU = cpuUsage();
|
|
13
|
+
const mem = memoryUsage();
|
|
14
|
+
return {
|
|
15
|
+
eventLoopLagP95Ms: histogram.percentile(95) / 1e6,
|
|
16
|
+
eventLoopLagMaxMs: histogram.max / 1e6,
|
|
17
|
+
heapUsedMb: mem.heapUsed / 1048576,
|
|
18
|
+
rssMb: mem.rss / 1048576,
|
|
19
|
+
externalMb: mem.external / 1048576,
|
|
20
|
+
cpuPercent: delta > 0 ? ((cpu.user + cpu.system) / 1000 / delta) * 100 : 0,
|
|
21
|
+
uptimeSeconds: process.uptime(),
|
|
22
|
+
};
|
|
23
|
+
},
|
|
24
|
+
close() {
|
|
25
|
+
histogram.disable();
|
|
26
|
+
},
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
//# sourceMappingURL=node-diagnostics.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"node-diagnostics.js","sourceRoot":"","sources":["../src/node-diagnostics.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAC;AACrE,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AACrD,+FAA+F;AAC/F,MAAM,UAAU,qBAAqB;IACnC,MAAM,SAAS,GAAG,qBAAqB,CAAC,EAAE,UAAU,EAAE,EAAE,EAAE,CAAC,CAAC;IAC5D,SAAS,CAAC,MAAM,EAAE,CAAC;IACnB,IAAI,WAAW,GAAG,QAAQ,EAAE,EAC1B,YAAY,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;IACnC,OAAO;QACL,QAAQ;YACN,MAAM,GAAG,GAAG,WAAW,CAAC,GAAG,EAAE,EAC3B,GAAG,GAAG,QAAQ,CAAC,WAAW,CAAC,EAC3B,KAAK,GAAG,GAAG,GAAG,YAAY,CAAC;YAC7B,YAAY,GAAG,GAAG,CAAC;YACnB,WAAW,GAAG,QAAQ,EAAE,CAAC;YACzB,MAAM,GAAG,GAAG,WAAW,EAAE,CAAC;YAC1B,OAAO;gBACL,iBAAiB,EAAE,SAAS,CAAC,UAAU,CAAC,EAAE,CAAC,GAAG,GAAG;gBACjD,iBAAiB,EAAE,SAAS,CAAC,GAAG,GAAG,GAAG;gBACtC,UAAU,EAAE,GAAG,CAAC,QAAQ,GAAG,OAAO;gBAClC,KAAK,EAAE,GAAG,CAAC,GAAG,GAAG,OAAO;gBACxB,UAAU,EAAE,GAAG,CAAC,QAAQ,GAAG,OAAO;gBAClC,UAAU,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,MAAM,CAAC,GAAG,IAAI,GAAG,KAAK,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC;gBAC1E,aAAa,EAAE,OAAO,CAAC,MAAM,EAAE;aAChC,CAAC;QACJ,CAAC;QACD,KAAK;YACH,SAAS,CAAC,OAAO,EAAE,CAAC;QACtB,CAAC;KACF,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export declare class RequestMetrics {
|
|
2
|
+
private count;
|
|
3
|
+
private errors;
|
|
4
|
+
private duration;
|
|
5
|
+
observe(status: number, ms: number): void;
|
|
6
|
+
snapshot(): {
|
|
7
|
+
requests: number;
|
|
8
|
+
errors: number;
|
|
9
|
+
availability: number | null;
|
|
10
|
+
meanMs: number | null;
|
|
11
|
+
};
|
|
12
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export class RequestMetrics {
|
|
2
|
+
count = 0;
|
|
3
|
+
errors = 0;
|
|
4
|
+
duration = 0;
|
|
5
|
+
observe(status, ms) {
|
|
6
|
+
this.count++;
|
|
7
|
+
if (status >= 500)
|
|
8
|
+
this.errors++;
|
|
9
|
+
this.duration += ms;
|
|
10
|
+
}
|
|
11
|
+
snapshot() {
|
|
12
|
+
return {
|
|
13
|
+
requests: this.count,
|
|
14
|
+
errors: this.errors,
|
|
15
|
+
availability: this.count ? 1 - this.errors / this.count : null,
|
|
16
|
+
meanMs: this.count ? this.duration / this.count : null,
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
//# sourceMappingURL=request-metrics.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"request-metrics.js","sourceRoot":"","sources":["../src/request-metrics.ts"],"names":[],"mappings":"AAAA,MAAM,OAAO,cAAc;IACjB,KAAK,GAAG,CAAC,CAAC;IACV,MAAM,GAAG,CAAC,CAAC;IACX,QAAQ,GAAG,CAAC,CAAC;IACrB,OAAO,CAAC,MAAc,EAAE,EAAU;QAChC,IAAI,CAAC,KAAK,EAAE,CAAC;QACb,IAAI,MAAM,IAAI,GAAG;YAAE,IAAI,CAAC,MAAM,EAAE,CAAC;QACjC,IAAI,CAAC,QAAQ,IAAI,EAAE,CAAC;IACtB,CAAC;IACD,QAAQ;QACN,OAAO;YACL,QAAQ,EAAE,IAAI,CAAC,KAAK;YACpB,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,YAAY,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI;YAC9D,MAAM,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI;SACvD,CAAC;IACJ,CAAC;CACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,44 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@saplings/observability",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Structured backend logs, OpenTelemetry helpers, and Node.js process metrics",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"default": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist",
|
|
16
|
+
"README.md",
|
|
17
|
+
"CHANGELOG.md"
|
|
18
|
+
],
|
|
19
|
+
"engines": {
|
|
20
|
+
"node": ">=22"
|
|
21
|
+
},
|
|
22
|
+
"dependencies": {
|
|
23
|
+
"@opentelemetry/api": "^1.10.0"
|
|
24
|
+
},
|
|
25
|
+
"devDependencies": {
|
|
26
|
+
"@opentelemetry/context-async-hooks": "3.1.1",
|
|
27
|
+
"@opentelemetry/sdk-metrics": "3.1.1",
|
|
28
|
+
"@opentelemetry/sdk-trace": "3.1.1",
|
|
29
|
+
"@types/node": "^26.0.0"
|
|
30
|
+
},
|
|
31
|
+
"license": "MIT",
|
|
32
|
+
"repository": {
|
|
33
|
+
"type": "git",
|
|
34
|
+
"url": "git+https://github.com/snrakshith/saplings.git",
|
|
35
|
+
"directory": "packages/observability"
|
|
36
|
+
},
|
|
37
|
+
"publishConfig": {
|
|
38
|
+
"access": "public",
|
|
39
|
+
"registry": "https://registry.npmjs.org/"
|
|
40
|
+
},
|
|
41
|
+
"scripts": {
|
|
42
|
+
"build": "tsc -p ."
|
|
43
|
+
}
|
|
6
44
|
}
|