@moonwatch/js 0.1.12 → 0.1.13
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 +36 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -130,6 +130,42 @@ logger.setGroup(undefined);
|
|
|
130
130
|
logger.setTraceId(undefined);
|
|
131
131
|
```
|
|
132
132
|
|
|
133
|
+
### Dynamic Trace ID Provider
|
|
134
|
+
|
|
135
|
+
For server-side applications handling concurrent requests, use `setTraceIdProvider` to dynamically resolve the trace ID per log entry. This works with Node.js `AsyncLocalStorage` to associate every log (including intercepted `console.log` calls) with the request that triggered it:
|
|
136
|
+
|
|
137
|
+
```ts
|
|
138
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
139
|
+
import { randomUUID } from "node:crypto";
|
|
140
|
+
import { createLogger } from "@moonwatch/js";
|
|
141
|
+
|
|
142
|
+
const traceStorage = new AsyncLocalStorage<string>();
|
|
143
|
+
|
|
144
|
+
const logger = createLogger({
|
|
145
|
+
logId: "your-log-file-id",
|
|
146
|
+
apiKey: "your-api-key",
|
|
147
|
+
silent: true,
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
// Register the provider — called on every log to resolve the current trace ID
|
|
151
|
+
logger.setTraceIdProvider(() => traceStorage.getStore());
|
|
152
|
+
logger.interceptConsole();
|
|
153
|
+
|
|
154
|
+
// In your HTTP middleware:
|
|
155
|
+
app.use(async (ctx, next) => {
|
|
156
|
+
const traceId = randomUUID();
|
|
157
|
+
await traceStorage.run(traceId, next);
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
// Now any console.log during a request automatically gets that request's trace ID
|
|
161
|
+
console.log("processing order"); // → trace_id: "the-request-uuid"
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
The provider is checked on every log call with the following priority:
|
|
165
|
+
1. Per-call `traceId` (via object form or `ScopedLogger`)
|
|
166
|
+
2. `traceIdProvider()` return value
|
|
167
|
+
3. Static `traceId` from config / `setTraceId()`
|
|
168
|
+
|
|
133
169
|
## Console Interception
|
|
134
170
|
|
|
135
171
|
Capture existing `console.*` calls without changing application code:
|