@tracelumo/node 0.6.0 → 0.7.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 CHANGED
@@ -1,6 +1,6 @@
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, 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.
3
+ `@tracelumo/node` connects a Node.js app to TraceLumo. It traces every incoming and outgoing request — Node HTTP and HTTPS, Express, built-in `fetch`, MongoDB and Mongoose, PostgreSQL, MySQL and Redis (ioredis and node-redis) — 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
 
@@ -56,10 +56,15 @@ NODE_OPTIONS="--require @tracelumo/node/register" npm run dev
56
56
  | `TRACELUMO_METRICS` | `true` | Set to `false` to stop sending system metrics. |
57
57
  | `TRACELUMO_METRICS_INTERVAL` | `15` | Seconds between metric samples (5 to 300). |
58
58
  | `TRACELUMO_HEARTBEAT_INTERVAL` | `1` | Seconds between heartbeats (1 to 60); `0` turns them off. |
59
+ | `TRACELUMO_STACK_FRAMES` | `100` | Stack frames kept on errors (10 to 1000). Node.js keeps 10 by default; the SDK raises it, never lowers it. |
59
60
  | `TRACELUMO_ENABLED` | `true` | Set to `false` to turn the SDK off. |
60
61
 
61
62
  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`.
62
63
 
64
+ **Traces:** every request is kept (no sampling). Database calls record the query's shape: MongoDB filter values and
65
+ Redis arguments are replaced before recording; SQL is recorded as written, so use parameters (`$1`, `?`) for values.
66
+ Request headers and bodies are never recorded. Failed calls carry their exception and error message.
67
+
63
68
  **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.
64
69
 
65
70
  **System metrics:** every 15 seconds the SDK records the process's CPU, memory (RSS, heap), event loop delay and
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tracelumo/node",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
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",
@@ -39,6 +39,12 @@
39
39
  "@opentelemetry/instrumentation": "^0.301.2",
40
40
  "@opentelemetry/instrumentation-express": "^0.73.0",
41
41
  "@opentelemetry/instrumentation-http": "^0.301.2",
42
+ "@opentelemetry/instrumentation-ioredis": "^0.73.0",
43
+ "@opentelemetry/instrumentation-mongodb": "^0.78.0",
44
+ "@opentelemetry/instrumentation-mongoose": "^0.71.0",
45
+ "@opentelemetry/instrumentation-mysql2": "^0.71.0",
46
+ "@opentelemetry/instrumentation-pg": "^0.78.0",
47
+ "@opentelemetry/instrumentation-redis": "^0.73.0",
42
48
  "@opentelemetry/instrumentation-undici": "^0.35.1",
43
49
  "@opentelemetry/otlp-exporter-base": "0.301.2",
44
50
  "@opentelemetry/otlp-transformer": "0.301.2",
package/src/config.cjs CHANGED
@@ -68,10 +68,14 @@ function configuration(options = {}, cwd = process.cwd(), environment = process.
68
68
  // Seconds between heartbeats: 1 by default, up to 60; 0 turns them off (metrics samples still go out).
69
69
  const beat = Number(options.heartbeatInterval ?? setting('TRACELUMO_HEARTBEAT_INTERVAL') ?? 1);
70
70
  const heartbeatInterval = Number.isFinite(beat) ? (beat <= 0 ? 0 : Math.min(60, Math.max(1, Math.round(beat)))) : 1;
71
+ // Stack frames kept on errors: 100 by default, 10 to 1000 (Node.js itself keeps 10).
72
+ const frames = Number(options.stackFrames ?? setting('TRACELUMO_STACK_FRAMES') ?? 100);
73
+ const stackFrames = Number.isFinite(frames) ? Math.min(1000, Math.max(10, Math.round(frames))) : 100;
71
74
  const base = url.replace(/\/v1\/traces$/, '');
72
75
  return {
73
76
  url, logsUrl: `${base}/v1/ingest/logs`, errorsUrl: `${base}/v1/ingest/errors`, metricsUrl: `${base}/v1/ingest/metrics`,
74
77
  heartbeatUrl: `${base}/v1/ingest/heartbeat`, token, service, logs, metrics, metricsInterval, heartbeatInterval,
78
+ stackFrames,
75
79
  };
76
80
  }
77
81
 
package/src/index.cjs CHANGED
@@ -9,6 +9,8 @@ function start(options) {
9
9
  if (globalThis[instance]) return;
10
10
  const config = configuration(options);
11
11
  if (!config) return;
12
+ // Node.js keeps only 10 stack frames by default; keep enough to see the whole path to an error.
13
+ if (Error.stackTraceLimit < config.stackFrames) Error.stackTraceLimit = config.stackFrames;
12
14
 
13
15
  const { context, isSpanContextValid, propagation, trace } = require('@opentelemetry/api');
14
16
  const { AsyncLocalStorageContextManager } = require('@opentelemetry/context-async-hooks');
@@ -17,6 +19,13 @@ function start(options) {
17
19
  const { ExpressInstrumentation } = require('@opentelemetry/instrumentation-express');
18
20
  const { HttpInstrumentation } = require('@opentelemetry/instrumentation-http');
19
21
  const { UndiciInstrumentation } = require('@opentelemetry/instrumentation-undici');
22
+ // Outgoing database and cache calls. Each one only patches its library if the app actually uses it.
23
+ const { MongoDBInstrumentation } = require('@opentelemetry/instrumentation-mongodb');
24
+ const { MongooseInstrumentation } = require('@opentelemetry/instrumentation-mongoose');
25
+ const { PgInstrumentation } = require('@opentelemetry/instrumentation-pg');
26
+ const { MySQL2Instrumentation } = require('@opentelemetry/instrumentation-mysql2');
27
+ const { IORedisInstrumentation } = require('@opentelemetry/instrumentation-ioredis');
28
+ const { RedisInstrumentation } = require('@opentelemetry/instrumentation-redis');
20
29
  const { resourceFromAttributes } = require('@opentelemetry/resources');
21
30
  const { TracerProvider, BatchSpanProcessor } = require('@opentelemetry/sdk-trace');
22
31
 
@@ -24,16 +33,20 @@ function start(options) {
24
33
 
25
34
  const provider = new TracerProvider({
26
35
  resource: resourceFromAttributes({ 'service.name': config.service }),
36
+ // Enough room for full details: database statements, addresses and exceptions with their whole stack.
27
37
  spanLimits: {
28
- attributeCountLimit: 32,
29
- attributeValueLengthLimit: 128,
30
- eventCountLimit: 0,
38
+ attributeCountLimit: 64,
39
+ attributeValueLengthLimit: 16384,
40
+ eventCountLimit: 16,
41
+ attributePerEventCountLimit: 8,
31
42
  linkCountLimit: 0,
32
43
  },
44
+ // Every span is kept (no sampling). A large queue absorbs bursts; 256 spans per request stays under the
45
+ // server's limit of 512.
33
46
  spanProcessors: [new BatchSpanProcessor({
34
47
  exporter: createExporter(config),
35
- maxQueueSize: 1024,
36
- maxExportBatchSize: 64,
48
+ maxQueueSize: 16384,
49
+ maxExportBatchSize: 256,
37
50
  scheduledDelayMillis: 1000,
38
51
  exportTimeoutMillis: 6000,
39
52
  })],
@@ -53,6 +66,13 @@ function start(options) {
53
66
  new HttpInstrumentation(),
54
67
  new ExpressInstrumentation(),
55
68
  new UndiciInstrumentation(),
69
+ // Query shapes only: values in MongoDB filters and Redis arguments are replaced before they're recorded.
70
+ new MongoDBInstrumentation({ enhancedDatabaseReporting: false }),
71
+ new MongooseInstrumentation(),
72
+ new PgInstrumentation({ requireParentSpan: false }),
73
+ new MySQL2Instrumentation(),
74
+ new IORedisInstrumentation({ requireParentSpan: false }),
75
+ new RedisInstrumentation({ requireParentSpan: false }),
56
76
  ],
57
77
  });
58
78
  // Apply the HTTP hooks before an ESM application reads named built-in exports.
package/src/index.d.cts CHANGED
@@ -11,6 +11,8 @@ export interface TracingOptions {
11
11
  metricsInterval?: number;
12
12
  /** Seconds between heartbeats (current CPU and memory, online status), 1 to 60; 0 turns them off. Defaults to 1 (TRACELUMO_HEARTBEAT_INTERVAL). */
13
13
  heartbeatInterval?: number;
14
+ /** Stack frames kept on errors, 10 to 1000. Defaults to 100 (TRACELUMO_STACK_FRAMES). */
15
+ stackFrames?: number;
14
16
  }
15
17
 
16
18
  export function start(options?: TracingOptions): void;
package/src/metrics.cjs CHANGED
@@ -122,7 +122,8 @@ function createSampler({ service, cwd = process.cwd(), cgroup } = {}) {
122
122
  }
123
123
  let last = { at: performance.now(), cpu: process.cpuUsage(), system: cpuTimes(), elu: performance.eventLoopUtilization(), net: networkBytes() };
124
124
 
125
- function sample() {
125
+ /** One sample. `paused`: the process was suspended (serverless between requests), so delay readings are void. */
126
+ function sample({ paused = false } = {}) {
126
127
  const now = { at: performance.now(), cpu: process.cpuUsage(), system: cpuTimes(), elu: performance.eventLoopUtilization(), net: networkBytes() };
127
128
  const elapsedMs = Math.max(1, now.at - last.at);
128
129
  const cores = info.cpus || 1;
@@ -163,6 +164,13 @@ function createSampler({ service, cwd = process.cwd(), cgroup } = {}) {
163
164
  values.network_rx = round(Math.max(0, now.net.rx - last.net.rx) / (elapsedMs / 1000), 0);
164
165
  values.network_tx = round(Math.max(0, now.net.tx - last.net.tx) / (elapsedMs / 1000), 0);
165
166
  }
167
+ // A paused process (Vercel and Lambda freeze functions between requests) records the whole pause as event loop
168
+ // delay when it resumes. That's not a delay the app had, so leave those readings out.
169
+ if (paused) {
170
+ delete values.event_loop_p50;
171
+ delete values.event_loop_p99;
172
+ delete values.event_loop_max;
173
+ }
166
174
  for (const key of Object.keys(values)) if (values[key] === undefined) delete values[key];
167
175
  delay.reset();
168
176
  gcCount = 0;
@@ -212,13 +220,19 @@ function startHeartbeat({ heartbeatUrl, token }, { instance, sampler, seconds, s
212
220
  const agent = new transport.Agent({ keepAlive: true, maxSockets: 1 });
213
221
  let busy = false;
214
222
  let stopped = false;
223
+ let beats = 0;
215
224
  const send = () => {
216
225
  if (busy || stopped) return;
217
226
  let body;
218
227
  try {
228
+ // The first beat (and every 30th) carries the instance's details, so even a function that lives only a few
229
+ // seconds shows its platform and runtime.
230
+ const withInfo = beats % 30 === 0;
231
+ beats += 1;
219
232
  body = JSON.stringify({
220
233
  instance, timestamp: new Date().toISOString(), every: seconds,
221
234
  service: sampler.info.service, hostname: sampler.info.hostname, values: sampler.beat(),
235
+ ...(withInfo ? { info: sampler.info } : {}),
222
236
  });
223
237
  } catch {
224
238
  return;
@@ -255,14 +269,20 @@ function startMetrics({ metricsUrl, heartbeatUrl, token, service, metricsInterva
255
269
  if (details) Object.assign(sampler.info, defined(details));
256
270
  }).catch(() => {});
257
271
  const queue = createQueue({ url: metricsUrl, token, maxBatch: 100, kind: 'metrics' }, options);
272
+ // Serverless functions may live only seconds, so their first full sample comes after one second.
273
+ const firstSample = NOT_CONTAINERS.has(sampler.info.runtime) && sampler.info.runtime !== 'host' ? 1000 : Math.min(FIRST_SAMPLE, metricsInterval * 1000);
274
+ // When the sample timer fires far later than planned, the process was paused rather than busy.
275
+ let due = Date.now() + firstSample;
258
276
  const record = () => {
259
277
  try {
260
- queue.push({ instance, timestamp: new Date().toISOString(), info: sampler.info, values: sampler.sample() });
278
+ const late = Date.now() - due;
279
+ due = Date.now() + metricsInterval * 1000;
280
+ queue.push({ instance, timestamp: new Date().toISOString(), info: sampler.info, values: sampler.sample({ paused: late > Math.max(2000, metricsInterval * 500) }) });
261
281
  } catch {
262
282
  // Metrics must never break the application.
263
283
  }
264
284
  };
265
- const first = setTimeout(record, Math.min(FIRST_SAMPLE, metricsInterval * 1000));
285
+ const first = setTimeout(record, firstSample);
266
286
  first.unref();
267
287
  const timer = setInterval(record, metricsInterval * 1000);
268
288
  timer.unref();