@tracelumo/node 0.2.0 → 0.4.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/README.md +15 -5
- package/package.json +2 -2
- package/src/config.cjs +9 -1
- package/src/index.cjs +19 -7
- package/src/index.d.cts +4 -0
- package/src/init.cjs +1 -1
- package/src/logs.cjs +86 -17
- package/src/metrics.cjs +184 -0
package/README.md
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
# TraceLumo for Node.js
|
|
2
2
|
|
|
3
|
-
`@tracelumo/node` connects a Node.js app to TraceLumo. It traces Node HTTP and HTTPS, Express and built-in `fetch`, sends `console` output as logs linked to the active trace, and announces the service when it starts. Requires Node.js 22.15 or later.
|
|
3
|
+
`@tracelumo/node` connects a Node.js app to TraceLumo. It traces Node HTTP and HTTPS, Express and built-in `fetch`, sends `console` output as logs linked to the active trace, reports errors to error tracking, sends system and runtime metrics, and announces the service when it starts. No separate agent is needed. Requires Node.js 22.15 or later.
|
|
4
4
|
|
|
5
5
|
## Quick setup
|
|
6
6
|
|
|
7
7
|
Create a token on your project's **Agent tokens** page, then run this in your app's folder:
|
|
8
8
|
|
|
9
9
|
```sh
|
|
10
|
-
npx @tracelumo/node init --endpoint
|
|
10
|
+
npx @tracelumo/node init --endpoint https://your-tracelumo.vercel.app --token tl_agent_your_project_token
|
|
11
11
|
```
|
|
12
12
|
|
|
13
13
|
`init` installs the SDK, saves the endpoint and token to `.env.local` (and makes sure Git ignores it), and hooks the SDK into the app's normal start-up:
|
|
@@ -26,7 +26,7 @@ npm install @tracelumo/node
|
|
|
26
26
|
Set the endpoint and token in the app's environment or `.env.local`:
|
|
27
27
|
|
|
28
28
|
```dotenv
|
|
29
|
-
TRACELUMO_OTLP_ENDPOINT=
|
|
29
|
+
TRACELUMO_OTLP_ENDPOINT=https://your-tracelumo.vercel.app
|
|
30
30
|
TRACELUMO_AGENT_TOKEN=tl_agent_your_project_token
|
|
31
31
|
```
|
|
32
32
|
|
|
@@ -52,10 +52,20 @@ NODE_OPTIONS="--require @tracelumo/node/register" npm run dev
|
|
|
52
52
|
| `TRACELUMO_OTLP_ENDPOINT` | — | API address. Remote endpoints must use HTTPS. |
|
|
53
53
|
| `TRACELUMO_AGENT_TOKEN` | — | Project agent token. |
|
|
54
54
|
| `TRACELUMO_SERVICE_NAME` | `name` in package.json | Service name shown in TraceLumo. |
|
|
55
|
-
| `TRACELUMO_LOGS` | `true` | Set to `false` to stop sending console output as logs. |
|
|
55
|
+
| `TRACELUMO_LOGS` | `true` | Set to `false` to stop sending console output as logs and errors. |
|
|
56
|
+
| `TRACELUMO_METRICS` | `true` | Set to `false` to stop sending system metrics. |
|
|
57
|
+
| `TRACELUMO_METRICS_INTERVAL` | `15` | Seconds between metric samples (5 to 300). |
|
|
56
58
|
| `TRACELUMO_ENABLED` | `true` | Set to `false` to turn the SDK off. |
|
|
57
59
|
|
|
58
|
-
Logs are batched (up to 100 per request, sent every second) and capped at 8 KiB per line.
|
|
60
|
+
Logs are batched (up to 100 per request, sent every second) and capped at 8 KiB per line. Node.js process warnings are sent as `warn`, not `error`.
|
|
61
|
+
|
|
62
|
+
**Errors:** uncaught exceptions, unhandled promise rejections and any `Error` passed to `console.error` are sent to error tracking, where the same error from the same place is grouped into one issue. After an uncaught exception the SDK keeps Node's default behaviour — print the error and exit with code 1 — once the report is sent (at most 2 seconds), unless your app has its own `uncaughtException` handler. The SDK never traces or logs its own requests. Use a single OpenTelemetry setup per app: if you already register a tracer, replace it with this package.
|
|
63
|
+
|
|
64
|
+
**System metrics:** every 15 seconds the SDK records the process's CPU, memory (RSS, heap), event loop delay and
|
|
65
|
+
utilization, garbage collection pauses and open handles, plus the machine's CPU, memory, load average, disk and (on
|
|
66
|
+
Linux) network. It also records the host name, OS, CPU model, memory limit and Node.js version. Everything uses Node.js
|
|
67
|
+
built-ins inside your app: no agent or extra process. Samples are sent in batches every 30 seconds, and the timers never
|
|
68
|
+
keep your process alive. They appear on the project's **Infrastructure** page, one row per running instance.
|
|
59
69
|
|
|
60
70
|
## Lifecycle hooks
|
|
61
71
|
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tracelumo/node",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Connect Node.js apps to TraceLumo: automatic traces and
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "Connect Node.js apps to TraceLumo: automatic traces, logs, errors and system metrics",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "./src/index.cjs",
|
|
7
7
|
"bin": {
|
package/src/config.cjs
CHANGED
|
@@ -59,7 +59,15 @@ function configuration(options = {}, cwd = process.cwd(), environment = process.
|
|
|
59
59
|
}
|
|
60
60
|
const url = traceURL(endpoint);
|
|
61
61
|
const logs = options.logs ?? setting('TRACELUMO_LOGS') !== 'false';
|
|
62
|
-
|
|
62
|
+
const metrics = options.metrics ?? setting('TRACELUMO_METRICS') !== 'false';
|
|
63
|
+
// Seconds between metric samples: 15 by default, 5 to 300.
|
|
64
|
+
const requested = Number(options.metricsInterval ?? setting('TRACELUMO_METRICS_INTERVAL') ?? 15);
|
|
65
|
+
const metricsInterval = Number.isFinite(requested) ? Math.min(300, Math.max(5, Math.round(requested))) : 15;
|
|
66
|
+
const base = url.replace(/\/v1\/traces$/, '');
|
|
67
|
+
return {
|
|
68
|
+
url, logsUrl: `${base}/v1/ingest/logs`, errorsUrl: `${base}/v1/ingest/errors`, metricsUrl: `${base}/v1/ingest/metrics`,
|
|
69
|
+
token, service, logs, metrics, metricsInterval,
|
|
70
|
+
};
|
|
63
71
|
}
|
|
64
72
|
|
|
65
73
|
module.exports = { configuration, traceURL };
|
package/src/index.cjs
CHANGED
|
@@ -61,24 +61,35 @@ function start(options) {
|
|
|
61
61
|
syncBuiltinESMExports();
|
|
62
62
|
|
|
63
63
|
let logs = null;
|
|
64
|
+
let errors = null;
|
|
64
65
|
let restoreConsole = () => {};
|
|
66
|
+
let restoreCrashes = () => {};
|
|
65
67
|
if (config.logs) {
|
|
66
|
-
const { captureConsole, createLogShipper } = require('./logs.cjs');
|
|
67
|
-
|
|
68
|
-
|
|
68
|
+
const { captureConsole, captureCrashes, createErrorShipper, createLogShipper } = require('./logs.cjs');
|
|
69
|
+
const options = { suppress: (fn) => context.with(suppressTracing(context.active()), fn) };
|
|
70
|
+
const activeTrace = () => {
|
|
69
71
|
const span = trace.getSpanContext(context.active());
|
|
70
72
|
return span && isSpanContextValid(span) ? span.traceId : undefined;
|
|
71
|
-
}
|
|
73
|
+
};
|
|
74
|
+
logs = createLogShipper(config, options);
|
|
75
|
+
errors = createErrorShipper(config, options);
|
|
76
|
+
restoreConsole = captureConsole(logs, activeTrace, errors);
|
|
77
|
+
restoreCrashes = captureCrashes(errors, activeTrace);
|
|
72
78
|
// Announce the service as soon as it starts, so the project shows as connected before any request.
|
|
73
79
|
logs.add('info', `TraceLumo connected: ${config.service} started (Node.js ${process.version}, pid ${process.pid})`);
|
|
74
80
|
setImmediate(logs.flush);
|
|
75
81
|
}
|
|
76
|
-
|
|
82
|
+
let metrics = null;
|
|
83
|
+
if (config.metrics) {
|
|
84
|
+
const { startMetrics } = require('./metrics.cjs');
|
|
85
|
+
metrics = startMetrics(config, { suppress: (fn) => context.with(suppressTracing(context.active()), fn) });
|
|
86
|
+
}
|
|
87
|
+
globalThis[instance] = { provider, stopInstrumentation, logs, errors, metrics, restoreConsole, restoreCrashes };
|
|
77
88
|
}
|
|
78
89
|
|
|
79
90
|
async function flush() {
|
|
80
91
|
const sdk = globalThis[instance];
|
|
81
|
-
if (sdk) await Promise.all([sdk.stopping ?? sdk.provider.forceFlush(), sdk.logs?.flush()]);
|
|
92
|
+
if (sdk) await Promise.all([sdk.stopping ?? sdk.provider.forceFlush(), sdk.logs?.flush(), sdk.errors?.flush(), sdk.metrics?.flush()]);
|
|
82
93
|
}
|
|
83
94
|
|
|
84
95
|
async function shutdown() {
|
|
@@ -87,8 +98,9 @@ async function shutdown() {
|
|
|
87
98
|
if (!sdk.stopping) {
|
|
88
99
|
sdk.stopInstrumentation();
|
|
89
100
|
sdk.restoreConsole();
|
|
101
|
+
sdk.restoreCrashes();
|
|
90
102
|
syncBuiltinESMExports();
|
|
91
|
-
sdk.stopping = Promise.all([sdk.provider.shutdown(), sdk.logs?.close()]).then(() => {});
|
|
103
|
+
sdk.stopping = Promise.all([sdk.provider.shutdown(), sdk.logs?.close(), sdk.errors?.close(), sdk.metrics?.close()]).then(() => {});
|
|
92
104
|
}
|
|
93
105
|
await sdk.stopping;
|
|
94
106
|
}
|
package/src/index.d.cts
CHANGED
|
@@ -5,6 +5,10 @@ export interface TracingOptions {
|
|
|
5
5
|
enabled?: boolean;
|
|
6
6
|
/** Send console output as logs. Defaults to true; TRACELUMO_LOGS=false turns it off. */
|
|
7
7
|
logs?: boolean;
|
|
8
|
+
/** Send system and runtime metrics (CPU, memory, event loop, GC, disk). Defaults to true; TRACELUMO_METRICS=false turns it off. */
|
|
9
|
+
metrics?: boolean;
|
|
10
|
+
/** Seconds between metric samples, 5 to 300. Defaults to 15 (TRACELUMO_METRICS_INTERVAL). */
|
|
11
|
+
metricsInterval?: number;
|
|
8
12
|
}
|
|
9
13
|
|
|
10
14
|
export function start(options?: TracingOptions): void;
|
package/src/init.cjs
CHANGED
|
@@ -20,7 +20,7 @@ const usage = `Connect this app to TraceLumo.
|
|
|
20
20
|
Usage: npx @tracelumo/node init --endpoint <url> --token <tl_agent_…> [options]
|
|
21
21
|
|
|
22
22
|
Options:
|
|
23
|
-
--endpoint <url> TraceLumo
|
|
23
|
+
--endpoint <url> TraceLumo address, e.g. https://tracelumo.vercel.app
|
|
24
24
|
--token <token> Project agent token from the Agent tokens page
|
|
25
25
|
--service <name> Service name shown in TraceLumo (default: package.json name)
|
|
26
26
|
--package <spec> Install the SDK from this spec instead of npm (e.g. a local .tgz)
|
package/src/logs.cjs
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
const { randomUUID } = require('node:crypto');
|
|
4
4
|
const http = require('node:http');
|
|
5
5
|
const https = require('node:https');
|
|
6
|
-
const { format } = require('node:util');
|
|
6
|
+
const { format, inspect } = require('node:util');
|
|
7
7
|
const { gzipSync } = require('node:zlib');
|
|
8
8
|
|
|
9
9
|
// Limits match the TraceLumo log ingest API.
|
|
@@ -20,12 +20,12 @@ function clip(text) {
|
|
|
20
20
|
}
|
|
21
21
|
|
|
22
22
|
/**
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
23
|
+
* A batching queue that sends JSON events to one ingest API. Requests run with tracing suppressed so the SDK
|
|
24
|
+
* never traces or logs its own traffic. Transient failures are retried on the next tick; a rejected token is
|
|
25
|
+
* reported once and its events are dropped.
|
|
26
26
|
*/
|
|
27
|
-
function
|
|
28
|
-
const target = new URL(
|
|
27
|
+
function createQueue({ url, token, maxBatch, kind, interval = INTERVAL }, { suppress }) {
|
|
28
|
+
const target = new URL(url);
|
|
29
29
|
const transport = target.protocol === 'https:' ? https : http;
|
|
30
30
|
let queue = [];
|
|
31
31
|
let inflight = null;
|
|
@@ -58,7 +58,7 @@ function createLogShipper({ logsUrl, token, service }, { suppress }) {
|
|
|
58
58
|
|
|
59
59
|
async function drain() {
|
|
60
60
|
while (queue.length) {
|
|
61
|
-
const batch = queue.splice(0,
|
|
61
|
+
const batch = queue.splice(0, maxBatch);
|
|
62
62
|
const status = await post(batch);
|
|
63
63
|
if (status >= 200 && status < 300) continue;
|
|
64
64
|
if (status === 0 || status === 429 || status >= 500) {
|
|
@@ -67,7 +67,7 @@ function createLogShipper({ logsUrl, token, service }, { suppress }) {
|
|
|
67
67
|
}
|
|
68
68
|
if (!warned) {
|
|
69
69
|
warned = true;
|
|
70
|
-
process.emitWarning(`TraceLumo rejected a
|
|
70
|
+
process.emitWarning(`TraceLumo rejected a ${kind} batch (HTTP ${status}). Check TRACELUMO_AGENT_TOKEN.`, { code: 'TRACELUMO_LOGS' });
|
|
71
71
|
}
|
|
72
72
|
}
|
|
73
73
|
}
|
|
@@ -77,20 +77,18 @@ function createLogShipper({ logsUrl, token, service }, { suppress }) {
|
|
|
77
77
|
return inflight;
|
|
78
78
|
}
|
|
79
79
|
|
|
80
|
-
function
|
|
80
|
+
function push(event) {
|
|
81
81
|
if (queue.length >= MAX_QUEUE) queue.shift();
|
|
82
|
-
const event = { event_id: randomUUID(), timestamp: new Date().toISOString(), service, severity, body: clip(body) };
|
|
83
|
-
if (traceId) event.trace_id = traceId;
|
|
84
82
|
queue.push(event);
|
|
85
|
-
if (queue.length >=
|
|
83
|
+
if (queue.length >= maxBatch) setImmediate(flush);
|
|
86
84
|
}
|
|
87
85
|
|
|
88
|
-
const timer = setInterval(flush,
|
|
86
|
+
const timer = setInterval(flush, interval);
|
|
89
87
|
timer.unref();
|
|
90
88
|
process.once('beforeExit', () => { void flush(); });
|
|
91
89
|
|
|
92
90
|
return {
|
|
93
|
-
|
|
91
|
+
push,
|
|
94
92
|
flush,
|
|
95
93
|
async close() {
|
|
96
94
|
clearInterval(timer);
|
|
@@ -99,8 +97,56 @@ function createLogShipper({ logsUrl, token, service }, { suppress }) {
|
|
|
99
97
|
};
|
|
100
98
|
}
|
|
101
99
|
|
|
100
|
+
/** Sends console output as log events. */
|
|
101
|
+
function createLogShipper({ logsUrl, token, service }, options) {
|
|
102
|
+
const queue = createQueue({ url: logsUrl, token, maxBatch: MAX_BATCH, kind: 'log' }, options);
|
|
103
|
+
return {
|
|
104
|
+
add(severity, body, traceId) {
|
|
105
|
+
const event = { event_id: randomUUID(), timestamp: new Date().toISOString(), service, severity, body: clip(body) };
|
|
106
|
+
if (traceId) event.trace_id = traceId;
|
|
107
|
+
queue.push(event);
|
|
108
|
+
},
|
|
109
|
+
flush: queue.flush,
|
|
110
|
+
close: queue.close,
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Sends exceptions to error tracking, where they are grouped into issues. */
|
|
115
|
+
function createErrorShipper({ errorsUrl, token, service }, options) {
|
|
116
|
+
const queue = createQueue({ url: errorsUrl, token, maxBatch: 50, kind: 'error' }, options);
|
|
117
|
+
return {
|
|
118
|
+
add(error, { handled, traceId }) {
|
|
119
|
+
const isError = error instanceof Error;
|
|
120
|
+
const name = isError ? (error.name || error.constructor?.name || 'Error') : 'UnhandledRejection';
|
|
121
|
+
const event = {
|
|
122
|
+
event_id: randomUUID(),
|
|
123
|
+
timestamp: new Date().toISOString(),
|
|
124
|
+
service,
|
|
125
|
+
type: String(name).slice(0, 200),
|
|
126
|
+
message: String(isError ? error.message : inspect(error)).slice(0, 4000),
|
|
127
|
+
stack: isError && typeof error.stack === 'string' ? error.stack.slice(0, 32000) : '',
|
|
128
|
+
handled,
|
|
129
|
+
};
|
|
130
|
+
if (!event.message && !event.type) return;
|
|
131
|
+
if (traceId) event.trace_id = traceId;
|
|
132
|
+
queue.push(event);
|
|
133
|
+
},
|
|
134
|
+
flush: queue.flush,
|
|
135
|
+
close: queue.close,
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Node.js prints its own process warnings through console.error, e.g.
|
|
140
|
+
// "(node:7) ExperimentalWarning: …" or "(node:7) [DEP0040] DeprecationWarning: …". They are warnings, not errors.
|
|
141
|
+
const NODE_WARNING = /^\(node:\d+\)\s+(?:\[[A-Z0-9]+\]\s+)?[A-Za-z]*Warning:/;
|
|
142
|
+
|
|
143
|
+
/** The severity for a console call, correcting Node.js process warnings that arrive through console.error. */
|
|
144
|
+
function severityOf(severity, body) {
|
|
145
|
+
return severity === 'error' && NODE_WARNING.test(body) ? 'warn' : severity;
|
|
146
|
+
}
|
|
147
|
+
|
|
102
148
|
/** Mirrors console output to the shipper, tagged with the active trace. Returns a restore function. */
|
|
103
|
-
function captureConsole(shipper, traceId) {
|
|
149
|
+
function captureConsole(shipper, traceId, errors) {
|
|
104
150
|
const originals = {};
|
|
105
151
|
let busy = false;
|
|
106
152
|
for (const [method, severity] of Object.entries(METHODS)) {
|
|
@@ -114,7 +160,13 @@ function captureConsole(shipper, traceId) {
|
|
|
114
160
|
try {
|
|
115
161
|
let body = format(...args).replace(ANSI, '').trim();
|
|
116
162
|
if (method === 'trace') body = `Trace: ${body}`;
|
|
117
|
-
|
|
163
|
+
const trace = traceId();
|
|
164
|
+
if (body) shipper.add(severityOf(severity, body), body, trace);
|
|
165
|
+
// An Error passed to console.error (how frameworks such as Next.js report request errors) is also an error event.
|
|
166
|
+
if (errors && method === 'error') {
|
|
167
|
+
const error = args.find((arg) => arg instanceof Error);
|
|
168
|
+
if (error) errors.add(error, { handled: true, traceId: trace });
|
|
169
|
+
}
|
|
118
170
|
} catch {
|
|
119
171
|
// Logging must never break the application.
|
|
120
172
|
} finally {
|
|
@@ -127,4 +179,21 @@ function captureConsole(shipper, traceId) {
|
|
|
127
179
|
};
|
|
128
180
|
}
|
|
129
181
|
|
|
130
|
-
|
|
182
|
+
/**
|
|
183
|
+
* Reports uncaught exceptions and unhandled rejections. When TraceLumo's handler is the only one, it keeps
|
|
184
|
+
* Node's default behaviour — print the error and exit with code 1 — after giving the report up to 2 seconds.
|
|
185
|
+
*/
|
|
186
|
+
function captureCrashes(errors, traceId) {
|
|
187
|
+
async function onCrash(error, origin) {
|
|
188
|
+
errors.add(error, { handled: false, traceId: traceId() });
|
|
189
|
+
if (process.listenerCount('uncaughtException') > 1) return;
|
|
190
|
+
await Promise.race([errors.flush(), new Promise((resolve) => setTimeout(resolve, 2000).unref())]);
|
|
191
|
+
const label = origin === 'unhandledRejection' ? 'Unhandled rejection' : 'Uncaught exception';
|
|
192
|
+
process.stderr.write(`${label}: ${error instanceof Error ? error.stack ?? error.message : inspect(error)}\n`);
|
|
193
|
+
process.exit(1);
|
|
194
|
+
}
|
|
195
|
+
process.on('uncaughtException', onCrash);
|
|
196
|
+
return () => process.off('uncaughtException', onCrash);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
module.exports = { createQueue, createLogShipper, createErrorShipper, captureConsole, captureCrashes, clip, severityOf };
|
package/src/metrics.cjs
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { randomUUID } = require('node:crypto');
|
|
4
|
+
const { existsSync, readFileSync, statfsSync } = require('node:fs');
|
|
5
|
+
const os = require('node:os');
|
|
6
|
+
const { monitorEventLoopDelay, performance, PerformanceObserver } = require('node:perf_hooks');
|
|
7
|
+
const { createQueue } = require('./logs.cjs');
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* System and runtime metrics, collected inside the application with Node.js built-ins only — no agent, no extra
|
|
11
|
+
* process, no dependencies. Every interval it records one sample: process CPU and memory, heap, event loop delay
|
|
12
|
+
* and utilization, garbage collection, open handles, and the machine's CPU, memory, load, disk and (on Linux)
|
|
13
|
+
* network. Samples are batched and sent to TraceLumo; the timers never keep the process alive.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
const SEND_EVERY = 30_000;
|
|
17
|
+
const round = (value, digits = 2) => (Number.isFinite(value) ? Number(value.toFixed(digits)) : undefined);
|
|
18
|
+
const ms = (ns) => ns / 1e6;
|
|
19
|
+
|
|
20
|
+
/** Where the process runs, so the dashboard can explain what the machine numbers mean. */
|
|
21
|
+
function runtime(env = process.env) {
|
|
22
|
+
if (env.VERCEL) return 'vercel';
|
|
23
|
+
if (env.AWS_LAMBDA_FUNCTION_NAME) return 'aws-lambda';
|
|
24
|
+
if (env.K_SERVICE) return 'cloud-run';
|
|
25
|
+
if (env.KUBERNETES_SERVICE_HOST) return 'kubernetes';
|
|
26
|
+
if (existsSync('/.dockerenv')) return 'docker';
|
|
27
|
+
return 'host';
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Facts about the machine and process that rarely change. */
|
|
31
|
+
function hostInfo(service) {
|
|
32
|
+
const cpus = os.cpus();
|
|
33
|
+
const limit = typeof process.constrainedMemory === 'function' ? process.constrainedMemory() : 0;
|
|
34
|
+
return {
|
|
35
|
+
hostname: os.hostname().slice(0, 128),
|
|
36
|
+
service,
|
|
37
|
+
os: `${os.type()} ${os.release()}`.slice(0, 128),
|
|
38
|
+
platform: process.platform,
|
|
39
|
+
arch: process.arch,
|
|
40
|
+
cpu_model: (cpus[0]?.model ?? '').trim().slice(0, 128),
|
|
41
|
+
cpus: os.availableParallelism?.() ?? cpus.length,
|
|
42
|
+
memory_total: os.totalmem(),
|
|
43
|
+
// A container or cgroup memory limit, when one is set below the machine's memory.
|
|
44
|
+
...(limit > 0 && limit < os.totalmem() ? { memory_limit: limit } : {}),
|
|
45
|
+
node: process.version,
|
|
46
|
+
pid: process.pid,
|
|
47
|
+
runtime: runtime(),
|
|
48
|
+
started: new Date(Date.now() - process.uptime() * 1000).toISOString(),
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function cpuTimes() {
|
|
53
|
+
let idle = 0;
|
|
54
|
+
let total = 0;
|
|
55
|
+
for (const cpu of os.cpus()) {
|
|
56
|
+
const { user, nice, sys, irq, idle: free } = cpu.times;
|
|
57
|
+
idle += free;
|
|
58
|
+
total += user + nice + sys + irq + free;
|
|
59
|
+
}
|
|
60
|
+
return { idle, total };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Network bytes received and sent by all non-loopback interfaces (Linux only). */
|
|
64
|
+
function networkBytes() {
|
|
65
|
+
if (process.platform !== 'linux') return null;
|
|
66
|
+
try {
|
|
67
|
+
let rx = 0;
|
|
68
|
+
let tx = 0;
|
|
69
|
+
for (const line of readFileSync('/proc/net/dev', 'utf8').split('\n').slice(2)) {
|
|
70
|
+
const [name, data] = line.split(':');
|
|
71
|
+
if (!data || name.trim() === 'lo') continue;
|
|
72
|
+
const fields = data.trim().split(/\s+/).map(Number);
|
|
73
|
+
rx += fields[0];
|
|
74
|
+
tx += fields[8];
|
|
75
|
+
}
|
|
76
|
+
return { rx, tx };
|
|
77
|
+
} catch {
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function disk(path) {
|
|
83
|
+
try {
|
|
84
|
+
const stats = statfsSync(path);
|
|
85
|
+
const total = stats.blocks * stats.bsize;
|
|
86
|
+
return total > 0 ? { total, free: stats.bavail * stats.bsize } : null;
|
|
87
|
+
} catch {
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Measures one process. `sample()` returns the values since the previous call. */
|
|
93
|
+
function createSampler({ service, cwd = process.cwd() } = {}) {
|
|
94
|
+
const info = hostInfo(service);
|
|
95
|
+
const delay = monitorEventLoopDelay({ resolution: 20 });
|
|
96
|
+
delay.enable();
|
|
97
|
+
let gcCount = 0;
|
|
98
|
+
let gcPause = 0;
|
|
99
|
+
let gc = null;
|
|
100
|
+
try {
|
|
101
|
+
gc = new PerformanceObserver((list) => {
|
|
102
|
+
for (const entry of list.getEntries()) {
|
|
103
|
+
gcCount += 1;
|
|
104
|
+
gcPause += entry.duration;
|
|
105
|
+
}
|
|
106
|
+
});
|
|
107
|
+
gc.observe({ entryTypes: ['gc'] });
|
|
108
|
+
} catch {
|
|
109
|
+
gc = null;
|
|
110
|
+
}
|
|
111
|
+
let last = { at: performance.now(), cpu: process.cpuUsage(), system: cpuTimes(), elu: performance.eventLoopUtilization(), net: networkBytes() };
|
|
112
|
+
|
|
113
|
+
function sample() {
|
|
114
|
+
const now = { at: performance.now(), cpu: process.cpuUsage(), system: cpuTimes(), elu: performance.eventLoopUtilization(), net: networkBytes() };
|
|
115
|
+
const elapsedMs = Math.max(1, now.at - last.at);
|
|
116
|
+
const cores = info.cpus || 1;
|
|
117
|
+
const processCpu = ((now.cpu.user - last.cpu.user + now.cpu.system - last.cpu.system) / 1000 / elapsedMs / cores) * 100;
|
|
118
|
+
const systemTotal = now.system.total - last.system.total;
|
|
119
|
+
const systemCpu = systemTotal > 0 ? (1 - (now.system.idle - last.system.idle) / systemTotal) * 100 : undefined;
|
|
120
|
+
const elu = performance.eventLoopUtilization(now.elu, last.elu).utilization * 100;
|
|
121
|
+
const memory = process.memoryUsage();
|
|
122
|
+
const free = os.freemem();
|
|
123
|
+
const [load1, load5, load15] = os.loadavg();
|
|
124
|
+
const space = disk(cwd);
|
|
125
|
+
const values = {
|
|
126
|
+
process_cpu: round(Math.min(100, Math.max(0, processCpu))),
|
|
127
|
+
system_cpu: round(systemCpu),
|
|
128
|
+
rss: memory.rss,
|
|
129
|
+
heap_used: memory.heapUsed,
|
|
130
|
+
heap_total: memory.heapTotal,
|
|
131
|
+
external: memory.external,
|
|
132
|
+
system_memory_used: os.totalmem() - free,
|
|
133
|
+
event_loop_p50: round(ms(delay.percentile(50))),
|
|
134
|
+
event_loop_p99: round(ms(delay.percentile(99))),
|
|
135
|
+
event_loop_max: round(ms(delay.max)),
|
|
136
|
+
event_loop_utilization: round(elu),
|
|
137
|
+
gc_count: gcCount,
|
|
138
|
+
gc_pause: round(gcPause),
|
|
139
|
+
handles: typeof process.getActiveResourcesInfo === 'function' ? process.getActiveResourcesInfo().length : undefined,
|
|
140
|
+
...(info.platform === 'win32' ? {} : { load_1: round(load1), load_5: round(load5), load_15: round(load15) }),
|
|
141
|
+
...(space ? { disk_total: space.total, disk_used: space.total - space.free } : {}),
|
|
142
|
+
uptime: Math.round(process.uptime()),
|
|
143
|
+
};
|
|
144
|
+
if (now.net && last.net) {
|
|
145
|
+
values.network_rx = round(Math.max(0, now.net.rx - last.net.rx) / (elapsedMs / 1000), 0);
|
|
146
|
+
values.network_tx = round(Math.max(0, now.net.tx - last.net.tx) / (elapsedMs / 1000), 0);
|
|
147
|
+
}
|
|
148
|
+
for (const key of Object.keys(values)) if (values[key] === undefined) delete values[key];
|
|
149
|
+
delay.reset();
|
|
150
|
+
gcCount = 0;
|
|
151
|
+
gcPause = 0;
|
|
152
|
+
last = now;
|
|
153
|
+
return values;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
return { info, sample, stop: () => { delay.disable(); gc?.disconnect(); } };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Samples every `interval` seconds and sends the samples to TraceLumo in batches. */
|
|
160
|
+
function startMetrics({ metricsUrl, token, service, metricsInterval }, options) {
|
|
161
|
+
const sampler = createSampler({ service });
|
|
162
|
+
const instance = randomUUID();
|
|
163
|
+
const queue = createQueue({ url: metricsUrl, token, maxBatch: 100, kind: 'metrics', interval: SEND_EVERY }, options);
|
|
164
|
+
const record = () => {
|
|
165
|
+
try {
|
|
166
|
+
queue.push({ instance, timestamp: new Date().toISOString(), info: sampler.info, values: sampler.sample() });
|
|
167
|
+
} catch {
|
|
168
|
+
// Metrics must never break the application.
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
const timer = setInterval(record, metricsInterval * 1000);
|
|
172
|
+
timer.unref();
|
|
173
|
+
return {
|
|
174
|
+
flush: queue.flush,
|
|
175
|
+
async close() {
|
|
176
|
+
clearInterval(timer);
|
|
177
|
+
record();
|
|
178
|
+
sampler.stop();
|
|
179
|
+
await queue.close();
|
|
180
|
+
},
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
module.exports = { createSampler, startMetrics, hostInfo, runtime };
|