@nestjs/observe 0.3.0 → 0.3.1

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.
@@ -62,14 +62,27 @@ let LoggerPatcherService = LoggerPatcherService_1 = class LoggerPatcherService {
62
62
  }
63
63
  return jsonLogObject;
64
64
  };
65
- ConsoleLogger.prototype["formatMessage"] = function (logLevel, message, pidMessage, formattedLogLevel, contextMessage, timestampDiff) {
65
+ ConsoleLogger.prototype["formatMessage"] = function (
66
+ // Everything Nest passes is forwarded untouched. Naming the parameters
67
+ // once pinned this wrapper to one release's signature: Nest 12 added a
68
+ // seventh (`params`), and a wrapper that forwarded six silently dropped
69
+ // every structured param from text-mode output.
70
+ ...args) {
71
+ const output = originalFormatMessage.apply(this, args);
66
72
  const store = asyncLocalStorage.getStore();
67
73
  const requestId = store?.get(options.traceIdKey);
68
- const output = originalFormatMessage.call(this, logLevel, message, pidMessage, formattedLogLevel, contextMessage, timestampDiff);
69
- if (requestId) {
70
- return `${output} Trace ID: ${this.colorize(requestId, logLevel)}\n`;
74
+ if (!requestId) {
75
+ return output;
71
76
  }
72
- return output;
77
+ // The suffix has to sit before the line's own newline. Appended after
78
+ // it, the id lands on a line of its own - which the stdout forwarder
79
+ // then ships as a separate, level-less entry, and the parser (which
80
+ // reads the id off the end of the log line) never sees it.
81
+ const [logLevel] = args;
82
+ const suffix = ` Trace ID: ${this.colorize(requestId, logLevel)}`;
83
+ return output.endsWith("\n")
84
+ ? `${output.slice(0, -1)}${suffix}\n`
85
+ : `${output}${suffix}`;
73
86
  };
74
87
  // Add watermark to flag that the logger has been patched
75
88
  Reflect.defineProperty(ConsoleLogger.prototype, this.patchedWatermark, {
@@ -8,13 +8,16 @@ export declare class StdoutForwarderService implements OnModuleInit, OnModuleDes
8
8
  private readonly als;
9
9
  private readonly logger;
10
10
  /**
11
- * stdout arrives in chunks, not lines: a single write can carry half a line,
11
+ * Output arrives in chunks, not lines: a single write can carry half a line,
12
12
  * several lines, or a line split across two calls. Parsing a chunk directly
13
13
  * would mangle every log that straddles a boundary, so the trailing fragment
14
14
  * is held here until its newline shows up.
15
+ *
16
+ * One fragment per stream: stdout and stderr interleave freely, and joining
17
+ * the tail of one onto the head of the other would fuse two unrelated lines.
15
18
  */
16
- private partialLine;
17
- private originalWrite;
19
+ private readonly partialLines;
20
+ private originalWrites;
18
21
  /**
19
22
  * Null only when redaction has been switched off explicitly. Defaulting to on
20
23
  * matters more here than anywhere else in the agent: enabling `forwardLogs`
@@ -25,9 +28,16 @@ export declare class StdoutForwarderService implements OnModuleInit, OnModuleDes
25
28
  constructor(options: ObserveModuleOptionsWithDefaults, observeAgentSharedBuffer: ObserveAgentSharedBuffer, als: AsyncLocalStorage<Map<string, any>>);
26
29
  onModuleInit(): void;
27
30
  onModuleDestroy(): void;
31
+ /**
32
+ * Patches both stdout and stderr. Nest's `ConsoleLogger` writes `error` to
33
+ * stderr and every other level to stdout, so a stdout-only patch forwarded
34
+ * warnings and fatals but never a single error - including the line the
35
+ * exceptions handler writes for every unhandled exception.
36
+ */
28
37
  start(): void;
38
+ private patch;
29
39
  /**
30
- * Restores the original stdout.write.
40
+ * Restores the original stdout and stderr writes.
31
41
  *
32
42
  * Without this the patch outlives the module - which matters in tests, where
33
43
  * a torn-down app would keep pushing into a buffer nobody drains, and in any
@@ -42,19 +42,26 @@ const MAX_PARTIAL_LINE_LENGTH = 8 * 1024;
42
42
  * inside this window, so it is redacted before the cut can split it.
43
43
  */
44
44
  const MAX_PARSED_LINE_LENGTH = 16 * 1024;
45
+ const FORWARDED_STREAMS = ["stdout", "stderr"];
45
46
  let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderService {
46
47
  options;
47
48
  observeAgentSharedBuffer;
48
49
  als;
49
50
  logger = new Logger(StdoutForwarderService_1.name);
50
51
  /**
51
- * stdout arrives in chunks, not lines: a single write can carry half a line,
52
+ * Output arrives in chunks, not lines: a single write can carry half a line,
52
53
  * several lines, or a line split across two calls. Parsing a chunk directly
53
54
  * would mangle every log that straddles a boundary, so the trailing fragment
54
55
  * is held here until its newline shows up.
56
+ *
57
+ * One fragment per stream: stdout and stderr interleave freely, and joining
58
+ * the tail of one onto the head of the other would fuse two unrelated lines.
55
59
  */
56
- partialLine = "";
57
- originalWrite = null;
60
+ partialLines = {
61
+ stdout: "",
62
+ stderr: "",
63
+ };
64
+ originalWrites = null;
58
65
  /**
59
66
  * Null only when redaction has been switched off explicitly. Defaulting to on
60
67
  * matters more here than anywhere else in the agent: enabling `forwardLogs`
@@ -82,22 +89,37 @@ let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderSer
82
89
  onModuleDestroy() {
83
90
  this.restore();
84
91
  }
92
+ /**
93
+ * Patches both stdout and stderr. Nest's `ConsoleLogger` writes `error` to
94
+ * stderr and every other level to stdout, so a stdout-only patch forwarded
95
+ * warnings and fatals but never a single error - including the line the
96
+ * exceptions handler writes for every unhandled exception.
97
+ */
85
98
  start() {
86
- if (this.originalWrite) {
99
+ if (this.originalWrites) {
87
100
  return;
88
101
  }
89
- // The unbound original is kept, so `restore` puts back exactly what was
102
+ // The unbound originals are kept, so `restore` puts back exactly what was
90
103
  // there. Storing the bound copy instead meant every start/restore cycle
91
104
  // left one more `bind` wrapper on the stream - and this module is designed
92
105
  // to be torn down and recreated.
93
- this.originalWrite = process.stdout.write;
94
- const originalWrite = process.stdout.write.bind(process.stdout);
95
- process.stdout.write = ((chunk, encoding, callback) => {
106
+ this.originalWrites = {
107
+ stdout: process.stdout.write,
108
+ stderr: process.stderr.write,
109
+ };
110
+ for (const name of FORWARDED_STREAMS) {
111
+ this.patch(name);
112
+ }
113
+ }
114
+ patch(name) {
115
+ const stream = process[name];
116
+ const originalWrite = stream.write.bind(stream);
117
+ stream.write = ((chunk, encoding, callback) => {
96
118
  if (typeof chunk === "string") {
97
119
  // Never let a forwarding failure take down the write it wrapped -
98
- // stdout has to keep working even if telemetry does not.
120
+ // the stream has to keep working even if telemetry does not.
99
121
  try {
100
- this.consume(chunk);
122
+ this.consume(chunk, name);
101
123
  }
102
124
  catch {
103
125
  // Intentionally silent: logging here would re-enter this same patched
@@ -108,43 +130,45 @@ let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderSer
108
130
  });
109
131
  }
110
132
  /**
111
- * Restores the original stdout.write.
133
+ * Restores the original stdout and stderr writes.
112
134
  *
113
135
  * Without this the patch outlives the module - which matters in tests, where
114
136
  * a torn-down app would keep pushing into a buffer nobody drains, and in any
115
137
  * process that recreates the Nest application.
116
138
  */
117
139
  restore() {
118
- if (!this.originalWrite) {
140
+ if (!this.originalWrites) {
119
141
  return;
120
142
  }
121
- this.flushPartial();
122
- process.stdout.write = this.originalWrite;
123
- this.originalWrite = null;
143
+ for (const name of FORWARDED_STREAMS) {
144
+ this.flushPartial(name);
145
+ process[name].write = this.originalWrites[name];
146
+ }
147
+ this.originalWrites = null;
124
148
  }
125
- consume(chunk) {
126
- const combined = this.partialLine + chunk;
149
+ consume(chunk, name = "stdout") {
150
+ const combined = this.partialLines[name] + chunk;
127
151
  const segments = combined.split("\n");
128
152
  // The final segment has no newline yet, so it is either an incomplete line
129
153
  // or the empty string left by a chunk that ended cleanly.
130
- this.partialLine = segments.pop() ?? "";
154
+ this.partialLines[name] = segments.pop() ?? "";
131
155
  const entries = segments
132
156
  .filter((line) => line.trim().length > 0)
133
157
  .map((line) => this.toLogEntry(line));
134
158
  if (entries.length > 0) {
135
159
  this.observeAgentSharedBuffer.pushLogs(entries);
136
160
  }
137
- if (this.partialLine.length > MAX_PARTIAL_LINE_LENGTH) {
138
- this.flushPartial();
161
+ if (this.partialLines[name].length > MAX_PARTIAL_LINE_LENGTH) {
162
+ this.flushPartial(name);
139
163
  }
140
164
  }
141
- flushPartial() {
142
- if (this.partialLine.trim().length === 0) {
143
- this.partialLine = "";
165
+ flushPartial(name) {
166
+ const partialLine = this.partialLines[name];
167
+ this.partialLines[name] = "";
168
+ if (partialLine.trim().length === 0) {
144
169
  return;
145
170
  }
146
- this.observeAgentSharedBuffer.pushLogs([this.toLogEntry(this.partialLine)]);
147
- this.partialLine = "";
171
+ this.observeAgentSharedBuffer.pushLogs([this.toLogEntry(partialLine)]);
148
172
  }
149
173
  toLogEntry(rawLine) {
150
174
  const line = rawLine.length > MAX_PARSED_LINE_LENGTH
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nestjs/observe",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "Observability and APM agent for NestJS - traces, runtime metrics, custom metrics and CPU profiles",
5
5
  "author": "Kamil Mysliwiec",
6
6
  "homepage": "https://observe.nestjs.com",