@zharp/node 0.2.0 → 0.3.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 +8 -6
- package/dist/index.d.mts +27 -2
- package/dist/index.d.ts +27 -2
- package/dist/index.js +288 -19
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +285 -16
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -37,7 +37,7 @@ node --import ./instrument.js server.js
|
|
|
37
37
|
|
|
38
38
|
Loading it first is what makes it work: the instrumentations patch `http`, your framework and your database driver as they are first imported, so `init()` has to run before any of them are. With CommonJS, `node --require ./instrument.js server.js` does the same.
|
|
39
39
|
|
|
40
|
-
With nothing but environment variables: `ZHARP_API_KEY=… ZHARP_SERVICE=checkout-api node --import @zharp/node/init server.js` (also `ZHARP_ENV`, `ZHARP_RELEASE`, `
|
|
40
|
+
With nothing but environment variables: `ZHARP_API_KEY=… ZHARP_SERVICE=checkout-api node --import @zharp/node/init server.js` (also `ZHARP_ENV`, `ZHARP_RELEASE`, `ZHARP_LOGS`; `ZHARP_DISABLED=true` turns it off).
|
|
41
41
|
|
|
42
42
|
### Next.js
|
|
43
43
|
|
|
@@ -60,7 +60,7 @@ The Edge runtime is not supported. If the build complains about OpenTelemetry mo
|
|
|
60
60
|
|---|---|
|
|
61
61
|
| **Requests** | A SERVER span per incoming request (`http.request.method`, `http.route` where the framework knows it, `http.response.status_code`; 5xx are errors), CLIENT spans for outgoing HTTP, and spans for database and cache calls. `dns`, `net` and `fs` are off — one span per lookup or file read is noise. |
|
|
62
62
|
| **Traces from the browser** | The `traceparent` header continues the browser's trace; `session.id` and `enduser.id` from the `baggage` header are copied onto every span and log of that request. |
|
|
63
|
-
| **Logs** | `Zharp.
|
|
63
|
+
| **Logs** | Every line the app prints during a request is stamped `trace_id=… span_id=…` (fields in JSON records), so the Zharp agent's copy of the app's output is linked to its request. With `logs: true` (`ZHARP_LOGS=true`) — for serverless or a host without the agent — the SDK sends them itself: `console.*`, pino, winston, bunyan and anything else printed, each with its trace and span. `Zharp.log.*` is always sent. |
|
|
64
64
|
| **Errors** | `Zharp.captureError(err)` (handled), uncaught exceptions and unhandled rejections (unhandled). Sent as error logs with `exception.type`, `exception.message` and `exception.stacktrace`, grouped into issues. |
|
|
65
65
|
|
|
66
66
|
### Uncaught exceptions
|
|
@@ -77,7 +77,7 @@ What is waiting is sent when the event loop empties, and on SIGTERM/SIGINT (afte
|
|
|
77
77
|
Zharp.init({ tracing: false }); // or ZHARP_TRACING=false
|
|
78
78
|
```
|
|
79
79
|
|
|
80
|
-
Logs (`Zharp.log.*`, the console, pino, winston, bunyan), errors (with `exception.*` and the handled flag), the user, the session and tags are sent as usual. No spans are exported, nothing is instrumented except the log bridges and the incoming side of `http`, and no `traceparent` or `baggage` is added to outgoing requests. An incoming `traceparent` and `baggage` are still read, so a request's logs carry the caller's trace id, session and user (and `setUser()` inside a request stays with that request) — at the cost of one never-exported in-memory span per request. `Zharp.startSpan(name, fn)` just runs `fn`.
|
|
80
|
+
Logs (`Zharp.log.*`, and with `logs: true` the console, pino, winston, bunyan), errors (with `exception.*` and the handled flag), the user, the session and tags are sent as usual. No spans are exported, nothing is instrumented except the log bridges and the incoming side of `http`, and no `traceparent` or `baggage` is added to outgoing requests. An incoming `traceparent` and `baggage` are still read, so a request's logs carry the caller's trace id, session and user (and `setUser()` inside a request stays with that request) — at the cost of one never-exported in-memory span per request. `Zharp.startSpan(name, fn)` just runs `fn`.
|
|
81
81
|
|
|
82
82
|
## API
|
|
83
83
|
|
|
@@ -103,16 +103,18 @@ Everything else is plain OpenTelemetry: `trace.getActiveSpan()`, `trace.getTrace
|
|
|
103
103
|
| `service` | `ZHARP_SERVICE`, `OTEL_SERVICE_NAME`, package.json name | `service.name` |
|
|
104
104
|
| `environment` | `ZHARP_ENV`, `NODE_ENV` | `deployment.environment.name` |
|
|
105
105
|
| `release` | `ZHARP_RELEASE` | `service.version` |
|
|
106
|
-
| `endpoint` | `https://api.zharp.io/api/v1/otlp` | |
|
|
107
106
|
| `tracing` | `ZHARP_TRACING`, else `true` | `false` for logs only (see above). |
|
|
108
107
|
| `sampleRate` | `1` | Fraction of new traces kept. A trace that arrives with a decision (from the browser) keeps it. Errors and logs are always sent. |
|
|
109
|
-
| `
|
|
108
|
+
| `logs` | `ZHARP_LOGS`, else `false` | Send what the app logs and prints. Off by default: where the Zharp agent reads the app's output it brings those lines in, linked by `logCorrelation`. Turn on for serverless or hosts without the agent. Errors, `Zharp.log` and traces are sent either way. |
|
|
109
|
+
| `logCorrelation` | `ZHARP_LOG_CORRELATION`, else `true` | Stamps `trace_id=… span_id=…` on each line printed during a request (fields in JSON records), so Zharp links it to the request. |
|
|
110
|
+
| `captureConsole` | `true` | With `logs` on. |
|
|
111
|
+
| `captureOutput` | `ZHARP_CAPTURE_OUTPUT`, else `true` | With `logs` on: everything else printed to stdout/stderr: NestJS's Logger, debug, log4js, anything writing to `process.stdout`. Level read from the line; keeps the request it was printed in; never sends a line twice. |
|
|
110
112
|
| `captureUncaught` | `true` | |
|
|
111
113
|
| `instrumentations` | | Per-instrumentation config for `getNodeAutoInstrumentations`, e.g. `{ '@opentelemetry/instrumentation-fs': { enabled: true } }`. |
|
|
112
114
|
| `extraInstrumentations` | `[]` | More OpenTelemetry instrumentations. |
|
|
113
115
|
| `debug` | `false` | Print what OpenTelemetry is doing. |
|
|
114
116
|
|
|
115
|
-
Traces and logs go as OTLP/protobuf, gzipped
|
|
117
|
+
Traces, errors and logs go straight to Zharp as OTLP/protobuf, gzipped.
|
|
116
118
|
|
|
117
119
|
## Readable stack traces
|
|
118
120
|
|
package/dist/index.d.mts
CHANGED
|
@@ -75,11 +75,36 @@ interface NodeOptions {
|
|
|
75
75
|
*/
|
|
76
76
|
tracing?: boolean;
|
|
77
77
|
/**
|
|
78
|
-
* Send
|
|
78
|
+
* Send what the application logs — `console`, pino, winston, bunyan and everything else it
|
|
79
|
+
* prints. Default **false**: where the Zharp agent reads the app's output it already brings
|
|
80
|
+
* those lines in, linked to their requests by the ids stamped on them (see `logCorrelation`).
|
|
81
|
+
* Turn it on where nothing else collects the output (serverless, a plain VM without the
|
|
82
|
+
* agent). Falls back to `ZHARP_LOGS` (`true` turns it on). Errors, `Zharp.log` and traces are
|
|
83
|
+
* sent either way. `captureConsole` and `captureOutput` refine what is sent when this is on.
|
|
84
|
+
*/
|
|
85
|
+
logs?: boolean;
|
|
86
|
+
/**
|
|
87
|
+
* Stamp the request's ids on every line printed during it — `trace_id=… span_id=…` at the end
|
|
88
|
+
* of a text line, two fields in a JSON record — so Zharp links the line to its request
|
|
89
|
+
* whichever way it arrives. Default **true**. Falls back to `ZHARP_LOG_CORRELATION`.
|
|
90
|
+
*/
|
|
91
|
+
logCorrelation?: boolean;
|
|
92
|
+
/**
|
|
93
|
+
* With `logs` on: send `console.*` output as logs. Default **true**: on a server, the console is where most
|
|
79
94
|
* logging already goes. pino, winston and bunyan are bridged by their instrumentations
|
|
80
95
|
* whatever this says.
|
|
81
96
|
*/
|
|
82
97
|
captureConsole?: boolean;
|
|
98
|
+
/**
|
|
99
|
+
* With `logs` on: send everything else the process prints as logs too: whatever reaches stdout or stderr
|
|
100
|
+
* without going through `console` or a bridged library — NestJS's Logger, debug, log4js,
|
|
101
|
+
* libraries writing to `process.stdout` directly. Default **true**. Each line keeps the
|
|
102
|
+
* request it was printed in; its level is read from the line (a JSON record's `level`,
|
|
103
|
+
* NestJS's `LOG`/`WARN`/`ERROR`, a word such as `ERROR`), else info on stdout and warn on
|
|
104
|
+
* stderr. A line another capture already sent is not sent again. `false` (or
|
|
105
|
+
* `ZHARP_CAPTURE_OUTPUT=false`) turns it off.
|
|
106
|
+
*/
|
|
107
|
+
captureOutput?: boolean;
|
|
83
108
|
/**
|
|
84
109
|
* Request and response bodies on HTTP spans — incoming requests and outgoing http/https
|
|
85
110
|
* calls. Default **off**. `'errors'` (or `true`) keeps them for failed requests only (status
|
|
@@ -184,7 +209,7 @@ declare class ZharpNode {
|
|
|
184
209
|
}
|
|
185
210
|
|
|
186
211
|
/** Sent as `telemetry.sdk.version`. Bumped with package.json. */
|
|
187
|
-
declare const VERSION = "0.
|
|
212
|
+
declare const VERSION = "0.3.0";
|
|
188
213
|
|
|
189
214
|
declare const Zharp: ZharpNode;
|
|
190
215
|
|
package/dist/index.d.ts
CHANGED
|
@@ -75,11 +75,36 @@ interface NodeOptions {
|
|
|
75
75
|
*/
|
|
76
76
|
tracing?: boolean;
|
|
77
77
|
/**
|
|
78
|
-
* Send
|
|
78
|
+
* Send what the application logs — `console`, pino, winston, bunyan and everything else it
|
|
79
|
+
* prints. Default **false**: where the Zharp agent reads the app's output it already brings
|
|
80
|
+
* those lines in, linked to their requests by the ids stamped on them (see `logCorrelation`).
|
|
81
|
+
* Turn it on where nothing else collects the output (serverless, a plain VM without the
|
|
82
|
+
* agent). Falls back to `ZHARP_LOGS` (`true` turns it on). Errors, `Zharp.log` and traces are
|
|
83
|
+
* sent either way. `captureConsole` and `captureOutput` refine what is sent when this is on.
|
|
84
|
+
*/
|
|
85
|
+
logs?: boolean;
|
|
86
|
+
/**
|
|
87
|
+
* Stamp the request's ids on every line printed during it — `trace_id=… span_id=…` at the end
|
|
88
|
+
* of a text line, two fields in a JSON record — so Zharp links the line to its request
|
|
89
|
+
* whichever way it arrives. Default **true**. Falls back to `ZHARP_LOG_CORRELATION`.
|
|
90
|
+
*/
|
|
91
|
+
logCorrelation?: boolean;
|
|
92
|
+
/**
|
|
93
|
+
* With `logs` on: send `console.*` output as logs. Default **true**: on a server, the console is where most
|
|
79
94
|
* logging already goes. pino, winston and bunyan are bridged by their instrumentations
|
|
80
95
|
* whatever this says.
|
|
81
96
|
*/
|
|
82
97
|
captureConsole?: boolean;
|
|
98
|
+
/**
|
|
99
|
+
* With `logs` on: send everything else the process prints as logs too: whatever reaches stdout or stderr
|
|
100
|
+
* without going through `console` or a bridged library — NestJS's Logger, debug, log4js,
|
|
101
|
+
* libraries writing to `process.stdout` directly. Default **true**. Each line keeps the
|
|
102
|
+
* request it was printed in; its level is read from the line (a JSON record's `level`,
|
|
103
|
+
* NestJS's `LOG`/`WARN`/`ERROR`, a word such as `ERROR`), else info on stdout and warn on
|
|
104
|
+
* stderr. A line another capture already sent is not sent again. `false` (or
|
|
105
|
+
* `ZHARP_CAPTURE_OUTPUT=false`) turns it off.
|
|
106
|
+
*/
|
|
107
|
+
captureOutput?: boolean;
|
|
83
108
|
/**
|
|
84
109
|
* Request and response bodies on HTTP spans — incoming requests and outgoing http/https
|
|
85
110
|
* calls. Default **off**. `'errors'` (or `true`) keeps them for failed requests only (status
|
|
@@ -184,7 +209,7 @@ declare class ZharpNode {
|
|
|
184
209
|
}
|
|
185
210
|
|
|
186
211
|
/** Sent as `telemetry.sdk.version`. Bumped with package.json. */
|
|
187
|
-
declare const VERSION = "0.
|
|
212
|
+
declare const VERSION = "0.3.0";
|
|
188
213
|
|
|
189
214
|
declare const Zharp: ZharpNode;
|
|
190
215
|
|
package/dist/index.js
CHANGED
|
@@ -33,7 +33,7 @@ var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
|
|
|
33
33
|
|
|
34
34
|
// src/zharp.ts
|
|
35
35
|
var import_node_module = require("module");
|
|
36
|
-
var
|
|
36
|
+
var import_api4 = require("@opentelemetry/api");
|
|
37
37
|
var import_core = require("@opentelemetry/core");
|
|
38
38
|
var import_resources = require("@opentelemetry/resources");
|
|
39
39
|
var import_sdk_node = require("@opentelemetry/sdk-node");
|
|
@@ -210,24 +210,24 @@ function shorten(value) {
|
|
|
210
210
|
if (BASE64.test(value) && /[0-9+/]/.test(value)) return `[base64 \xB7 ${formatSize(Math.floor(value.length * 3 / 4))}]`;
|
|
211
211
|
return value;
|
|
212
212
|
}
|
|
213
|
-
function filterAll(value,
|
|
214
|
-
if (
|
|
213
|
+
function filterAll(value, depth2) {
|
|
214
|
+
if (depth2 > 20) return FILTERED;
|
|
215
215
|
if (value === null || value === "") return value;
|
|
216
|
-
if (Array.isArray(value)) return value.map((v) => filterAll(v,
|
|
216
|
+
if (Array.isArray(value)) return value.map((v) => filterAll(v, depth2 + 1));
|
|
217
217
|
if (typeof value === "object") {
|
|
218
218
|
const out = {};
|
|
219
|
-
for (const [k, v] of Object.entries(value)) out[k] = filterAll(v,
|
|
219
|
+
for (const [k, v] of Object.entries(value)) out[k] = filterAll(v, depth2 + 1);
|
|
220
220
|
return out;
|
|
221
221
|
}
|
|
222
222
|
return FILTERED;
|
|
223
223
|
}
|
|
224
|
-
function redactValue(value, extra,
|
|
224
|
+
function redactValue(value, extra, depth2 = 0) {
|
|
225
225
|
if (typeof value === "string") return shorten(value);
|
|
226
|
-
if (
|
|
227
|
-
if (Array.isArray(value)) return value.map((v) => redactValue(v, extra,
|
|
226
|
+
if (depth2 > 20 || value === null || typeof value !== "object") return value;
|
|
227
|
+
if (Array.isArray(value)) return value.map((v) => redactValue(v, extra, depth2 + 1));
|
|
228
228
|
const out = {};
|
|
229
229
|
for (const [k, v] of Object.entries(value)) {
|
|
230
|
-
out[k] = isSecretKey(k, extra) ? filterAll(v,
|
|
230
|
+
out[k] = isSecretKey(k, extra) ? filterAll(v, depth2 + 1) : redactValue(v, extra, depth2 + 1);
|
|
231
231
|
}
|
|
232
232
|
return out;
|
|
233
233
|
}
|
|
@@ -812,6 +812,44 @@ var ContextLogProcessor = class {
|
|
|
812
812
|
// src/console.ts
|
|
813
813
|
var import_node_util = require("util");
|
|
814
814
|
var import_api2 = require("@opentelemetry/api");
|
|
815
|
+
|
|
816
|
+
// src/capture-state.ts
|
|
817
|
+
var depth = 0;
|
|
818
|
+
function quiet(fn) {
|
|
819
|
+
depth++;
|
|
820
|
+
try {
|
|
821
|
+
return fn();
|
|
822
|
+
} finally {
|
|
823
|
+
depth--;
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
var isQuiet = () => depth > 0;
|
|
827
|
+
var RECENT_MS = 3e3;
|
|
828
|
+
var RECENT_MAX = 500;
|
|
829
|
+
var recent = [];
|
|
830
|
+
var normalise = (text) => text.replace(/\s+/g, " ").trim();
|
|
831
|
+
function rememberSent(body) {
|
|
832
|
+
if (typeof body !== "string") return;
|
|
833
|
+
const text = normalise(body);
|
|
834
|
+
if (text.length < 4) return;
|
|
835
|
+
recent.push({ at: Date.now(), text });
|
|
836
|
+
if (recent.length > RECENT_MAX) recent.splice(0, recent.length - RECENT_MAX);
|
|
837
|
+
}
|
|
838
|
+
function alreadySent(line) {
|
|
839
|
+
const now = Date.now();
|
|
840
|
+
while (recent.length && now - recent[0].at > RECENT_MS) recent.shift();
|
|
841
|
+
if (!recent.length) return false;
|
|
842
|
+
const text = normalise(line);
|
|
843
|
+
for (let i = recent.length - 1; i >= 0; i--) {
|
|
844
|
+
if (text.includes(recent[i].text)) {
|
|
845
|
+
recent.splice(i, 1);
|
|
846
|
+
return true;
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
return false;
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
// src/console.ts
|
|
815
853
|
var LEVELS = [
|
|
816
854
|
["debug", import_api2.SeverityNumber.DEBUG, "DEBUG"],
|
|
817
855
|
["trace", import_api2.SeverityNumber.TRACE, "TRACE"],
|
|
@@ -828,7 +866,7 @@ function captureConsole(logger) {
|
|
|
828
866
|
if (typeof original !== "function" || original.__zharp) continue;
|
|
829
867
|
originals.set(method, original);
|
|
830
868
|
const patched = function(...args) {
|
|
831
|
-
original.apply(this ?? console, args);
|
|
869
|
+
quiet(() => original.apply(this ?? console, args));
|
|
832
870
|
if (emitting) return;
|
|
833
871
|
emitting = true;
|
|
834
872
|
try {
|
|
@@ -849,6 +887,207 @@ function captureConsole(logger) {
|
|
|
849
887
|
};
|
|
850
888
|
}
|
|
851
889
|
|
|
890
|
+
// src/stdout.ts
|
|
891
|
+
var import_api3 = require("@opentelemetry/api");
|
|
892
|
+
var LEVELS2 = {
|
|
893
|
+
trace: [import_api3.SeverityNumber.TRACE, "TRACE"],
|
|
894
|
+
verbose: [import_api3.SeverityNumber.DEBUG, "DEBUG"],
|
|
895
|
+
debug: [import_api3.SeverityNumber.DEBUG, "DEBUG"],
|
|
896
|
+
log: [import_api3.SeverityNumber.INFO, "INFO"],
|
|
897
|
+
info: [import_api3.SeverityNumber.INFO, "INFO"],
|
|
898
|
+
notice: [import_api3.SeverityNumber.INFO, "INFO"],
|
|
899
|
+
warn: [import_api3.SeverityNumber.WARN, "WARN"],
|
|
900
|
+
warning: [import_api3.SeverityNumber.WARN, "WARN"],
|
|
901
|
+
error: [import_api3.SeverityNumber.ERROR, "ERROR"],
|
|
902
|
+
err: [import_api3.SeverityNumber.ERROR, "ERROR"],
|
|
903
|
+
crit: [import_api3.SeverityNumber.FATAL, "FATAL"],
|
|
904
|
+
critical: [import_api3.SeverityNumber.FATAL, "FATAL"],
|
|
905
|
+
fatal: [import_api3.SeverityNumber.FATAL, "FATAL"],
|
|
906
|
+
emerg: [import_api3.SeverityNumber.FATAL, "FATAL"],
|
|
907
|
+
alert: [import_api3.SeverityNumber.FATAL, "FATAL"]
|
|
908
|
+
};
|
|
909
|
+
var NUMERIC = [[60, "fatal"], [50, "error"], [40, "warn"], [30, "info"], [20, "debug"], [0, "trace"]];
|
|
910
|
+
var ANSI = /\u001b\[[0-9;?]*[ -/]*[@-~]/g;
|
|
911
|
+
var NEST = /^\[Nest\]\s+\d+\s+-\s+.*?\s+(LOG|ERROR|WARN|DEBUG|VERBOSE|FATAL)\s+(?:\[([^\]]+)\]\s+)?([\s\S]*)$/;
|
|
912
|
+
var WORD = /(?:^|[\s[(|:=])(trace|verbose|debug|info|notice|warn(?:ing)?|err(?:or)?|crit(?:ical)?|fatal|emerg|alert)(?=$|[\s\]):|,])/i;
|
|
913
|
+
var MAX_LINE = 32 * 1024;
|
|
914
|
+
var FLUSH_MS = 200;
|
|
915
|
+
function levelOf(value) {
|
|
916
|
+
if (typeof value === "number") {
|
|
917
|
+
const found = NUMERIC.find(([n]) => value >= n);
|
|
918
|
+
return found ? LEVELS2[found[1]] : null;
|
|
919
|
+
}
|
|
920
|
+
return typeof value === "string" ? LEVELS2[value.toLowerCase()] ?? null : null;
|
|
921
|
+
}
|
|
922
|
+
function parseLine(raw) {
|
|
923
|
+
const line = raw.replace(ANSI, "").replace(/\s+$/, "");
|
|
924
|
+
if (line.startsWith("{") && line.endsWith("}")) {
|
|
925
|
+
try {
|
|
926
|
+
const record = JSON.parse(line);
|
|
927
|
+
const message = record.msg ?? record.message ?? record.event;
|
|
928
|
+
return {
|
|
929
|
+
level: levelOf(record.level ?? record.severity ?? record.lvl),
|
|
930
|
+
body: typeof message === "string" ? message : line,
|
|
931
|
+
attributes: {}
|
|
932
|
+
};
|
|
933
|
+
} catch {
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
const nest = NEST.exec(line);
|
|
937
|
+
if (nest) {
|
|
938
|
+
return {
|
|
939
|
+
level: LEVELS2[nest[1].toLowerCase()],
|
|
940
|
+
body: nest[3],
|
|
941
|
+
attributes: nest[2] ? { "log.logger": nest[2] } : {}
|
|
942
|
+
};
|
|
943
|
+
}
|
|
944
|
+
const word = WORD.exec(line.slice(0, 120));
|
|
945
|
+
return { level: word ? LEVELS2[word[1].toLowerCase()] ?? null : null, body: line, attributes: {} };
|
|
946
|
+
}
|
|
947
|
+
var SentLineProcessor = class {
|
|
948
|
+
onEmit(record) {
|
|
949
|
+
const source = record.attributes?.["log.source"];
|
|
950
|
+
if (source !== "stdout" && source !== "stderr") rememberSent(record.body);
|
|
951
|
+
}
|
|
952
|
+
forceFlush() {
|
|
953
|
+
return Promise.resolve();
|
|
954
|
+
}
|
|
955
|
+
shutdown() {
|
|
956
|
+
return Promise.resolve();
|
|
957
|
+
}
|
|
958
|
+
};
|
|
959
|
+
function captureOutput(logger) {
|
|
960
|
+
const undo = [];
|
|
961
|
+
for (const [stream, name, fallback] of [
|
|
962
|
+
[process.stdout, "stdout", LEVELS2.info],
|
|
963
|
+
[process.stderr, "stderr", LEVELS2.warn]
|
|
964
|
+
]) {
|
|
965
|
+
if (!stream || typeof stream.write !== "function" || stream.write.__zharp) continue;
|
|
966
|
+
const original = stream.write;
|
|
967
|
+
let pending = "";
|
|
968
|
+
let pendingContext;
|
|
969
|
+
let timer;
|
|
970
|
+
const emitLine = (line, ctx) => {
|
|
971
|
+
if (!line.trim() || line.includes("[Zharp]") || alreadySent(line)) return;
|
|
972
|
+
const parsed2 = parseLine(line.length > MAX_LINE ? line.slice(0, MAX_LINE) : line);
|
|
973
|
+
if (!parsed2.body.trim()) return;
|
|
974
|
+
const [severityNumber, severityText] = parsed2.level ?? fallback;
|
|
975
|
+
quiet(() => logger.emit({
|
|
976
|
+
severityNumber,
|
|
977
|
+
severityText,
|
|
978
|
+
body: parsed2.body,
|
|
979
|
+
attributes: { "log.source": name, "log.iostream": name, ...parsed2.attributes },
|
|
980
|
+
...ctx ? { context: ctx } : {}
|
|
981
|
+
}));
|
|
982
|
+
};
|
|
983
|
+
const flush = () => {
|
|
984
|
+
timer = void 0;
|
|
985
|
+
const line = pending;
|
|
986
|
+
const ctx = pendingContext;
|
|
987
|
+
pending = "";
|
|
988
|
+
pendingContext = void 0;
|
|
989
|
+
emitLine(line, ctx);
|
|
990
|
+
};
|
|
991
|
+
const take = (chunk, encoding) => {
|
|
992
|
+
if (isQuiet()) return;
|
|
993
|
+
const text = typeof chunk === "string" ? chunk : chunk instanceof Uint8Array ? Buffer.from(chunk).toString(typeof encoding === "string" ? encoding : "utf8") : "";
|
|
994
|
+
if (!text) return;
|
|
995
|
+
if (!pending) pendingContext = import_api3.context.active();
|
|
996
|
+
pending += text;
|
|
997
|
+
const lines = pending.split("\n");
|
|
998
|
+
pending = lines.pop() ?? "";
|
|
999
|
+
const ctx = pendingContext;
|
|
1000
|
+
if (pending) pendingContext = import_api3.context.active();
|
|
1001
|
+
for (const line of lines) emitLine(line, ctx);
|
|
1002
|
+
if (pending.length > MAX_LINE) flush();
|
|
1003
|
+
else if (pending && !timer) {
|
|
1004
|
+
timer = setTimeout(flush, FLUSH_MS);
|
|
1005
|
+
timer.unref?.();
|
|
1006
|
+
}
|
|
1007
|
+
};
|
|
1008
|
+
const patched = function(chunk, encoding, callback) {
|
|
1009
|
+
try {
|
|
1010
|
+
take(chunk, encoding);
|
|
1011
|
+
} catch {
|
|
1012
|
+
}
|
|
1013
|
+
return original.call(this ?? stream, chunk, encoding, callback);
|
|
1014
|
+
};
|
|
1015
|
+
patched.__zharp = true;
|
|
1016
|
+
stream.write = patched;
|
|
1017
|
+
undo.push(() => {
|
|
1018
|
+
if (timer) clearTimeout(timer);
|
|
1019
|
+
if (pending) flush();
|
|
1020
|
+
stream.write = original;
|
|
1021
|
+
});
|
|
1022
|
+
}
|
|
1023
|
+
return () => undo.forEach((fn) => fn());
|
|
1024
|
+
}
|
|
1025
|
+
function stampOutput() {
|
|
1026
|
+
const undo = [];
|
|
1027
|
+
for (const stream of [process.stdout, process.stderr]) {
|
|
1028
|
+
if (!stream || typeof stream.write !== "function" || stream.write.__zharpStamp) continue;
|
|
1029
|
+
const original = stream.write;
|
|
1030
|
+
const patched = function(chunk, encoding, callback) {
|
|
1031
|
+
let out = chunk;
|
|
1032
|
+
try {
|
|
1033
|
+
out = stamped(chunk, encoding);
|
|
1034
|
+
} catch {
|
|
1035
|
+
}
|
|
1036
|
+
return original.call(this ?? stream, out, encoding, callback);
|
|
1037
|
+
};
|
|
1038
|
+
patched.__zharpStamp = true;
|
|
1039
|
+
stream.write = patched;
|
|
1040
|
+
undo.push(() => {
|
|
1041
|
+
stream.write = original;
|
|
1042
|
+
});
|
|
1043
|
+
}
|
|
1044
|
+
return () => undo.forEach((fn) => fn());
|
|
1045
|
+
}
|
|
1046
|
+
function stamped(chunk, encoding) {
|
|
1047
|
+
const span = import_api3.trace.getActiveSpan()?.spanContext();
|
|
1048
|
+
if (!span || !(0, import_api3.isSpanContextValid)(span)) return chunk;
|
|
1049
|
+
const isBytes = chunk instanceof Uint8Array;
|
|
1050
|
+
if (typeof chunk !== "string" && !isBytes) return chunk;
|
|
1051
|
+
const enc = typeof encoding === "string" && Buffer.isEncoding(encoding) ? encoding : "utf8";
|
|
1052
|
+
if (isBytes && enc !== "utf8") return chunk;
|
|
1053
|
+
const text = isBytes ? Buffer.from(chunk).toString("utf8") : chunk;
|
|
1054
|
+
if (!text.includes("\n")) return chunk;
|
|
1055
|
+
const parts = text.split("\n");
|
|
1056
|
+
let last = -1;
|
|
1057
|
+
for (let i = parts.length - 2; i >= 0; i--) {
|
|
1058
|
+
if (parts[i].trim()) {
|
|
1059
|
+
last = i;
|
|
1060
|
+
break;
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
let changed = false;
|
|
1064
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
1065
|
+
if (i !== last && !parts[i].trimStart().startsWith("{")) continue;
|
|
1066
|
+
const next = stampLine(parts[i], span.traceId, span.spanId);
|
|
1067
|
+
if (next !== parts[i]) {
|
|
1068
|
+
parts[i] = next;
|
|
1069
|
+
changed = true;
|
|
1070
|
+
}
|
|
1071
|
+
}
|
|
1072
|
+
if (!changed) return chunk;
|
|
1073
|
+
const joined = parts.join("\n");
|
|
1074
|
+
return isBytes ? Buffer.from(joined, "utf8") : joined;
|
|
1075
|
+
}
|
|
1076
|
+
function stampLine(line, traceId, spanId) {
|
|
1077
|
+
const cr = line.endsWith("\r") ? "\r" : "";
|
|
1078
|
+
const body = cr ? line.slice(0, -1) : line;
|
|
1079
|
+
const trimmed = body.trimEnd();
|
|
1080
|
+
if (!trimmed.trim() || body.includes("trace_id") || body.includes("[Zharp]")) return line;
|
|
1081
|
+
if (trimmed.endsWith("}")) {
|
|
1082
|
+
if (!trimmed.trimStart().startsWith("{")) return line;
|
|
1083
|
+
const close = trimmed.lastIndexOf("}");
|
|
1084
|
+
const inner = trimmed.slice(trimmed.indexOf("{") + 1, close).trim();
|
|
1085
|
+
const fields = `"trace_id":"${traceId}","span_id":"${spanId}"`;
|
|
1086
|
+
return `${trimmed.slice(0, close)}${inner ? "," : ""}${fields}}${body.slice(trimmed.length)}${cr}`;
|
|
1087
|
+
}
|
|
1088
|
+
return `${trimmed} trace_id=${traceId} span_id=${spanId}${body.slice(trimmed.length)}${cr}`;
|
|
1089
|
+
}
|
|
1090
|
+
|
|
852
1091
|
// ../../internal/src/debug-ids.ts
|
|
853
1092
|
var DEBUG_IDS_ATTRIBUTE = "zharp.debug_ids";
|
|
854
1093
|
var files = /* @__PURE__ */ new Map();
|
|
@@ -996,7 +1235,7 @@ Caused by: ${cause.stack}`;
|
|
|
996
1235
|
}
|
|
997
1236
|
|
|
998
1237
|
// src/version.ts
|
|
999
|
-
var VERSION = "0.
|
|
1238
|
+
var VERSION = "0.3.0";
|
|
1000
1239
|
|
|
1001
1240
|
// src/zharp.ts
|
|
1002
1241
|
var DEFAULT_ENDPOINT = "https://api.zharp.io/api/v1/otlp";
|
|
@@ -1057,12 +1296,15 @@ var ZharpNode = class {
|
|
|
1057
1296
|
const endpoint = (pick(options.endpoint, nodeEnv("ZHARP_ENDPOINT")) ?? DEFAULT_ENDPOINT).replace(/\/+$/, "");
|
|
1058
1297
|
const tracing = tracingEnabled(options.tracing);
|
|
1059
1298
|
this.tracing = tracing;
|
|
1299
|
+
const sendLogs = switchOn(options.logs, "ZHARP_LOGS", false);
|
|
1300
|
+
const correlation = switchOn(options.logCorrelation, "ZHARP_LOG_CORRELATION", true);
|
|
1301
|
+
const bridges = logBridges(sendLogs, correlation, options.instrumentations);
|
|
1060
1302
|
if (options.debug) {
|
|
1061
1303
|
const out = { error: console.error, warn: console.warn, info: console.info, debug: console.debug, verbose: console.debug };
|
|
1062
1304
|
const prefixed = Object.fromEntries(
|
|
1063
1305
|
Object.entries(out).map(([level, fn]) => [level, (message, ...args) => fn.call(console, `[Zharp][otel] ${message}`, ...args)])
|
|
1064
1306
|
);
|
|
1065
|
-
|
|
1307
|
+
import_api4.diag.setLogger(prefixed, import_api4.DiagLogLevel.DEBUG);
|
|
1066
1308
|
}
|
|
1067
1309
|
registerEsmHook();
|
|
1068
1310
|
const headers = { Authorization: `Bearer ${key}` };
|
|
@@ -1074,6 +1316,7 @@ var ZharpNode = class {
|
|
|
1074
1316
|
new import_sdk_trace.BatchSpanProcessor({ exporter: new import_exporter_trace_otlp_proto.OTLPTraceExporter({ ...exporterOptions, url: `${endpoint}/v1/traces` }) })
|
|
1075
1317
|
] : [new ContextSpanProcessor(this.store)];
|
|
1076
1318
|
this.logProcessors = [
|
|
1319
|
+
new SentLineProcessor(),
|
|
1077
1320
|
new ContextLogProcessor(this.store),
|
|
1078
1321
|
new DebugIdLogProcessor(),
|
|
1079
1322
|
new import_sdk_logs.BatchLogRecordProcessor({ exporter: new import_exporter_logs_otlp_proto.OTLPLogExporter({ ...exporterOptions, url: `${endpoint}/v1/logs` }) })
|
|
@@ -1111,16 +1354,23 @@ var ZharpNode = class {
|
|
|
1111
1354
|
"@opentelemetry/instrumentation-net": { enabled: false },
|
|
1112
1355
|
"@opentelemetry/instrumentation-fs": { enabled: false },
|
|
1113
1356
|
...options.instrumentations,
|
|
1357
|
+
...bridges,
|
|
1114
1358
|
...bodies && {
|
|
1115
1359
|
"@opentelemetry/instrumentation-http": withBodyCapture(bodies, options.instrumentations?.["@opentelemetry/instrumentation-http"])
|
|
1116
1360
|
}
|
|
1117
|
-
}) : logsOnlyInstrumentations(options),
|
|
1361
|
+
}) : logsOnlyInstrumentations({ ...options, instrumentations: { ...options.instrumentations, ...bridges } }),
|
|
1118
1362
|
...options.extraInstrumentations ?? []
|
|
1119
1363
|
]
|
|
1120
1364
|
});
|
|
1121
1365
|
this.sdk.start();
|
|
1122
|
-
this.logger =
|
|
1123
|
-
if (
|
|
1366
|
+
this.logger = import_api4.logs.getLogger("@zharp/node", VERSION);
|
|
1367
|
+
if (correlation) this.teardowns.push(stampOutput());
|
|
1368
|
+
if (sendLogs) {
|
|
1369
|
+
if (options.captureConsole !== false) this.teardowns.push(captureConsole(this.logger));
|
|
1370
|
+
if (options.captureOutput !== false && nodeEnv("ZHARP_CAPTURE_OUTPUT") !== "false") {
|
|
1371
|
+
this.teardowns.push(captureOutput(this.logger));
|
|
1372
|
+
}
|
|
1373
|
+
}
|
|
1124
1374
|
if (options.captureUncaught !== false) this.teardowns.push(this.captureProcessErrors());
|
|
1125
1375
|
this.teardowns.push(this.flushOnExit());
|
|
1126
1376
|
announce(`Application monitoring active${tracing ? "" : " (logs only)"} \u2014 ${describeTarget(service, environment)}`);
|
|
@@ -1161,11 +1411,11 @@ var ZharpNode = class {
|
|
|
1161
1411
|
* throw or rejection marks the span as failed and is passed on unchanged.
|
|
1162
1412
|
*/
|
|
1163
1413
|
startSpan(name, fn, options = {}) {
|
|
1164
|
-
if (!this.tracing) return fn(
|
|
1165
|
-
const tracer =
|
|
1414
|
+
if (!this.tracing) return fn(import_api4.trace.wrapSpanContext(import_api4.trace.getActiveSpan()?.spanContext() ?? import_api4.INVALID_SPAN_CONTEXT));
|
|
1415
|
+
const tracer = import_api4.trace.getTracer("@zharp/node", VERSION);
|
|
1166
1416
|
return tracer.startActiveSpan(name, options, (span) => {
|
|
1167
1417
|
const fail = (error) => {
|
|
1168
|
-
span.setStatus({ code:
|
|
1418
|
+
span.setStatus({ code: import_api4.SpanStatusCode.ERROR, message: asError(error).message });
|
|
1169
1419
|
span.end();
|
|
1170
1420
|
};
|
|
1171
1421
|
let result;
|
|
@@ -1242,7 +1492,7 @@ var ZharpNode = class {
|
|
|
1242
1492
|
body: `${exception["exception.type"]}: ${exception["exception.message"]}`,
|
|
1243
1493
|
attributes: { ...attributes, ...exception }
|
|
1244
1494
|
});
|
|
1245
|
-
if (!handled)
|
|
1495
|
+
if (!handled) import_api4.trace.getActiveSpan()?.setStatus({ code: import_api4.SpanStatusCode.ERROR, message: error.message });
|
|
1246
1496
|
} catch {
|
|
1247
1497
|
}
|
|
1248
1498
|
}
|
|
@@ -1346,6 +1596,25 @@ function registerEsmHook() {
|
|
|
1346
1596
|
} catch {
|
|
1347
1597
|
}
|
|
1348
1598
|
}
|
|
1599
|
+
function switchOn(option, variable, fallback) {
|
|
1600
|
+
if (typeof option === "boolean") return option;
|
|
1601
|
+
const value = nodeEnv(variable);
|
|
1602
|
+
if (value && /^(true|1|yes|on)$/i.test(value)) return true;
|
|
1603
|
+
if (value && /^(false|0|no|off)$/i.test(value)) return false;
|
|
1604
|
+
return fallback;
|
|
1605
|
+
}
|
|
1606
|
+
function logBridges(sendLogs, correlation, own = {}) {
|
|
1607
|
+
const config = (name) => ({
|
|
1608
|
+
disableLogSending: !sendLogs,
|
|
1609
|
+
disableLogCorrelation: !correlation,
|
|
1610
|
+
...own[name]
|
|
1611
|
+
});
|
|
1612
|
+
return {
|
|
1613
|
+
"@opentelemetry/instrumentation-pino": config("@opentelemetry/instrumentation-pino"),
|
|
1614
|
+
"@opentelemetry/instrumentation-winston": config("@opentelemetry/instrumentation-winston"),
|
|
1615
|
+
"@opentelemetry/instrumentation-bunyan": config("@opentelemetry/instrumentation-bunyan")
|
|
1616
|
+
};
|
|
1617
|
+
}
|
|
1349
1618
|
function tracingEnabled(option) {
|
|
1350
1619
|
if (typeof option === "boolean") return option;
|
|
1351
1620
|
const value = nodeEnv("ZHARP_TRACING");
|