@warlock.js/logger 4.1.15 → 4.2.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/CHANGELOG.md +30 -0
- package/LICENSE +21 -0
- package/README.md +146 -145
- package/cjs/index.cjs +276 -11
- package/cjs/index.cjs.map +1 -1
- package/esm/channels/console-log.d.mts +1 -1
- package/esm/channels/console-log.d.mts.map +1 -1
- package/esm/channels/console-log.mjs +4 -1
- package/esm/channels/console-log.mjs.map +1 -1
- package/esm/channels/file-log.d.mts +13 -3
- package/esm/channels/file-log.d.mts.map +1 -1
- package/esm/channels/file-log.mjs +15 -1
- package/esm/channels/file-log.mjs.map +1 -1
- package/esm/channels/index.mjs +1 -0
- package/esm/channels/json-file-log.d.mts +1 -1
- package/esm/channels/json-file-log.d.mts.map +1 -1
- package/esm/channels/json-file-log.mjs +1 -1
- package/esm/channels/json-file-log.mjs.map +1 -1
- package/esm/channels/sentry-log.d.mts +182 -0
- package/esm/channels/sentry-log.d.mts.map +1 -0
- package/esm/channels/sentry-log.mjs +202 -0
- package/esm/channels/sentry-log.mjs.map +1 -0
- package/esm/index.d.mts +2 -1
- package/esm/index.mjs +2 -1
- package/esm/log-channel.d.mts +9 -1
- package/esm/log-channel.d.mts.map +1 -1
- package/esm/log-channel.mjs +1 -1
- package/esm/log-channel.mjs.map +1 -1
- package/esm/logger.d.mts +32 -1
- package/esm/logger.d.mts.map +1 -1
- package/esm/logger.mjs +44 -2
- package/esm/logger.mjs.map +1 -1
- package/esm/redact/redact.d.mts +1 -1
- package/esm/redact/redact.d.mts.map +1 -1
- package/esm/redact/redact.mjs +1 -1
- package/esm/redact/redact.mjs.map +1 -1
- package/esm/types.d.mts +19 -3
- package/esm/types.d.mts.map +1 -1
- package/esm/utils/capture-unhandled-errors.d.mts +9 -1
- package/esm/utils/capture-unhandled-errors.d.mts.map +1 -1
- package/esm/utils/capture-unhandled-errors.mjs +10 -2
- package/esm/utils/capture-unhandled-errors.mjs.map +1 -1
- package/esm/utils/clear-message.d.mts +1 -1
- package/esm/utils/clear-message.d.mts.map +1 -1
- package/esm/utils/clear-message.mjs +1 -1
- package/esm/utils/clear-message.mjs.map +1 -1
- package/esm/utils/safe-json-stringify.d.mts +1 -1
- package/esm/utils/safe-json-stringify.d.mts.map +1 -1
- package/esm/utils/safe-json-stringify.mjs +1 -1
- package/esm/utils/safe-json-stringify.mjs.map +1 -1
- package/llms-full.txt +1497 -1296
- package/llms.txt +20 -19
- package/package.json +5 -2
- package/skills/capture-unhandled-errors/SKILL.md +103 -103
- package/skills/filter-log-entries/SKILL.md +120 -120
- package/skills/flush-logs-on-shutdown/SKILL.md +117 -91
- package/skills/logger-basics/SKILL.md +88 -85
- package/skills/overview/SKILL.md +90 -86
- package/skills/pick-log-channel/SKILL.md +155 -139
- package/skills/ship-logs-to-sentry/SKILL.md +118 -0
- package/skills/write-custom-log-channel/SKILL.md +190 -160
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"log-channel.d.mts","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"log-channel.d.mts","names":[],"sources":["../../../../../../@warlock.js/logger/src/log-channel.ts"],"mappings":";;;uBAOsB,UAAA,iBACJ,sBAAA,GAAyB,sBAAA,aAC9B,WAAA;;AAFb;;EAMS,IAAA;EALS;;;EAUT,WAAA;EAyB6B;;;EApB7B,QAAA;EA0C4C;;;EAAA,UArCzC,qBAAA,EAAuB,OAAA;EA6EP;;;EAAA,UAxEhB,qBAAA,EAAuB,OAAA;EAgHyB;;;EAAA,UA3GhD,aAAA;EA7BY;;;cAkCH,cAAA,GAAiB,OAAA;EAnCK;;;EAAA,UAoD/B,IAAA,YAAgB,OAAA;EArCnB;;;EAAA,UA0CG,MAAA,iBAAuB,OAAA,EAAS,GAAA,EAAK,CAAA,GAAI,OAAA,CAAQ,CAAA;EAhC1B;;;EAAA,UAyCvB,iBAAA,CAAkB,cAAA,EAAgB,OAAA;EA/BzB;;;EAAA,UA2CT,cAAA,CAAe,IAAA,EAAM,WAAA;EArBd;;;EAAA,SAwCD,GAAA,CAAI,IAAA,EAAM,WAAA,UAAqB,OAAA;EAxCI;;;EA6C5C,SAAA;EApCqB;;;;;;;EA6CrB,KAAA,YAAiB,OAAA;EATjB;;;;;;EAiBA,eAAA,IAAmB,YAAA;;;;YAOhB,oBAAA;;;;EAWkE;;;EAAA,UAAlE,uBAAA,CAAwB,cAAA,EAAgB,OAAA,CAAQ,OAAA,IAAW,OAAA;AAAA"}
|
package/esm/log-channel.mjs
CHANGED
package/esm/log-channel.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"log-channel.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"log-channel.mjs","names":[],"sources":["../../../../../../@warlock.js/logger/src/log-channel.ts"],"sourcesContent":["import type {\r\n BasicLogConfigurations,\r\n LogContract,\r\n LoggingData,\r\n RedactConfig,\r\n} from \"./types\";\r\n\r\nexport abstract class LogChannel<\r\n Options extends BasicLogConfigurations = BasicLogConfigurations,\r\n> implements LogContract {\r\n /**\r\n * Channel name\r\n */\r\n public name!: string;\r\n\r\n /**\r\n * Channel description\r\n */\r\n public description?: string;\r\n\r\n /**\r\n * Determine if channel is logging in terminal\r\n */\r\n public terminal = false;\r\n\r\n /**\r\n * Default Configurations\r\n */\r\n protected defaultConfigurations: Options = {} as Options;\r\n\r\n /**\r\n * Channel configurations\r\n */\r\n protected channelConfigurations: Options = {} as Options; //\r\n\r\n /**\r\n * Determine whether the channel is fully initialized\r\n */\r\n protected isInitialized = false;\r\n\r\n /**\r\n * Constructor\r\n */\r\n public constructor(configurations?: Options) {\r\n if (configurations) {\r\n this.setConfigurations(configurations);\r\n }\r\n\r\n setTimeout(async () => {\r\n if (this.init) {\r\n await this.init();\r\n }\r\n\r\n this.isInitialized = true;\r\n }, 0);\r\n }\r\n\r\n /**\r\n * Initialize the channel\r\n */\r\n protected init?(): void | Promise<void>;\r\n\r\n /**\r\n * Get config value\r\n */\r\n protected config<K extends keyof Options>(key: K): Options[K] {\r\n return (\r\n this.channelConfigurations[key] ?? (this.defaultConfigurations ?? {})[key]\r\n );\r\n }\r\n\r\n /**\r\n * Set configurations\r\n */\r\n protected setConfigurations(configurations: Options) {\r\n this.channelConfigurations = {\r\n ...this.channelConfigurations,\r\n ...configurations,\r\n };\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Determine if the message should be logged\r\n */\r\n protected shouldBeLogged(data: LoggingData): boolean {\r\n // check for debug mode\r\n const allowedLevels = this.config(\"levels\");\r\n\r\n if (allowedLevels?.length && !allowedLevels.includes(data.type))\r\n return false;\r\n\r\n const filter = this.config(\"filter\");\r\n\r\n if (filter) {\r\n return filter(data);\r\n }\r\n\r\n return true;\r\n }\r\n\r\n /**\r\n * Log the given message\r\n */\r\n public abstract log(data: LoggingData): void | Promise<void>;\r\n\r\n /**\r\n * Synchronously flush messages\r\n */\r\n public flushSync?(): void;\r\n\r\n /**\r\n * Asynchronously flush buffered messages.\r\n *\r\n * Optional — channels that write synchronously per entry (e.g. `ConsoleLog`)\r\n * don't implement it. Buffering channels override this to drain their buffer\r\n * over async I/O so callers can `await log.flush()` on graceful shutdown.\r\n */\r\n public flush?(): void | Promise<void>;\r\n\r\n /**\r\n * Read the channel's redact config (if any). Used by `Logger` to apply\r\n * per-channel additive redaction on top of the logger-wide floor.\r\n * Subclasses normally don't override this — set `redact` in your channel\r\n * configuration instead.\r\n */\r\n public getRedactConfig(): RedactConfig | undefined {\r\n return this.config(\"redact\" as keyof Options) as RedactConfig | undefined;\r\n }\r\n\r\n /**\r\n * Get date and time formats\r\n */\r\n protected getDateAndTimeFormat() {\r\n const dateFormat = this.config(\"dateFormat\");\r\n const date = dateFormat?.date ?? \"DD-MM-YYYY\";\r\n const time = dateFormat?.time ?? \"HH:mm:ss\";\r\n\r\n return { date, time };\r\n }\r\n\r\n /**\r\n * get basic configurations with the given ones\r\n */\r\n protected withBasicConfigurations(configurations: Partial<Options>): Options {\r\n return {\r\n filter: () => true,\r\n ...configurations,\r\n } as any as Options;\r\n }\r\n}\r\n"],"mappings":";AAOA,IAAsB,aAAtB,MAEyB;;;;CAkCvB,AAAO,YAAY,gBAA0B;kBApB3B;+BAKyB,CAAC;+BAKD,CAAC;uBAKlB;EAMxB,IAAI,gBACF,KAAK,kBAAkB,cAAc;EAGvC,WAAW,YAAY;GACrB,IAAI,KAAK,MACP,MAAM,KAAK,KAAK;GAGlB,KAAK,gBAAgB;EACvB,GAAG,CAAC;CACN;;;;CAUA,AAAU,OAAgC,KAAoB;EAC5D,OACE,KAAK,sBAAsB,SAAS,KAAK,yBAAyB,CAAC,EAAC,CAAE;CAE1E;;;;CAKA,AAAU,kBAAkB,gBAAyB;EACnD,KAAK,wBAAwB;GAC3B,GAAG,KAAK;GACR,GAAG;EACL;EAEA,OAAO;CACT;;;;CAKA,AAAU,eAAe,MAA4B;EAEnD,MAAM,gBAAgB,KAAK,OAAO,QAAQ;EAE1C,IAAI,eAAe,UAAU,CAAC,cAAc,SAAS,KAAK,IAAI,GAC5D,OAAO;EAET,MAAM,SAAS,KAAK,OAAO,QAAQ;EAEnC,IAAI,QACF,OAAO,OAAO,IAAI;EAGpB,OAAO;CACT;;;;;;;CA2BA,AAAO,kBAA4C;EACjD,OAAO,KAAK,OAAO,QAAyB;CAC9C;;;;CAKA,AAAU,uBAAuB;EAC/B,MAAM,aAAa,KAAK,OAAO,YAAY;EAI3C,OAAO;GAAE,MAHI,YAAY,QAAQ;GAGlB,MAFF,YAAY,QAAQ;EAEb;CACtB;;;;CAKA,AAAU,wBAAwB,gBAA2C;EAC3E,OAAO;GACL,cAAc;GACd,GAAG;EACL;CACF;AACF"}
|
package/esm/logger.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { AutoFlushEvent, BasicLogConfigurations, LogLevel, LoggingData, OmittedLoggingData, RedactConfig } from "./types.mjs";
|
|
2
2
|
import { LogChannel } from "./log-channel.mjs";
|
|
3
3
|
|
|
4
|
-
//#region
|
|
4
|
+
//#region ../@warlock.js/logger/src/logger.d.ts
|
|
5
5
|
declare class Logger {
|
|
6
6
|
/**
|
|
7
7
|
* Current channel
|
|
@@ -110,6 +110,16 @@ declare class Logger {
|
|
|
110
110
|
* Make success log
|
|
111
111
|
*/
|
|
112
112
|
success(dataOrModule: OmittedLoggingData | string, action?: string, message?: any, context?: Record<string, any>): Promise<this>;
|
|
113
|
+
/**
|
|
114
|
+
* Make fatal log — for unrecoverable failures where the application is going
|
|
115
|
+
* down (failed bootstrap, lost connection to a required dependency that the
|
|
116
|
+
* caller has decided not to retry, an `uncaughtException`).
|
|
117
|
+
*
|
|
118
|
+
* Identical shape to {@link error}; the level is purely informational —
|
|
119
|
+
* `fatal` does NOT auto-flush or exit. The caller decides whether to call
|
|
120
|
+
* `await log.flush()` and `process.exit(...)`.
|
|
121
|
+
*/
|
|
122
|
+
fatal(dataOrModule: OmittedLoggingData | string, action?: string, message?: any, context?: Record<string, any>): Promise<this>;
|
|
113
123
|
/**
|
|
114
124
|
* Log an `error` entry when `condition` is falsy. No-op otherwise — the
|
|
115
125
|
* entry is never built and channels are not invoked, so this is genuinely
|
|
@@ -139,6 +149,27 @@ declare class Logger {
|
|
|
139
149
|
* Synchronously flush logs
|
|
140
150
|
*/
|
|
141
151
|
flushSync(): void;
|
|
152
|
+
/**
|
|
153
|
+
* Asynchronously drain every channel that implements `flush()`.
|
|
154
|
+
*
|
|
155
|
+
* Unlike {@link flushSync}, this awaits each channel's async I/O — the
|
|
156
|
+
* correct call for a graceful shutdown that can afford to wait
|
|
157
|
+
* (`await log.flush()` after closing the HTTP server, before
|
|
158
|
+
* `process.exit`). A channel whose delivery is async (a network transport,
|
|
159
|
+
* an async disk write) implements `flush()`, not `flushSync()`.
|
|
160
|
+
*
|
|
161
|
+
* Channels are isolated: a channel whose flush rejects can neither prevent
|
|
162
|
+
* the others from draining nor escape as an unhandled rejection. Channels
|
|
163
|
+
* without `flush()` are skipped.
|
|
164
|
+
*
|
|
165
|
+
* @example
|
|
166
|
+
* async function shutdown() {
|
|
167
|
+
* await httpServer.close();
|
|
168
|
+
* await log.flush();
|
|
169
|
+
* process.exit(0);
|
|
170
|
+
* }
|
|
171
|
+
*/
|
|
172
|
+
flush(): Promise<void>;
|
|
142
173
|
/**
|
|
143
174
|
* Register one process-level handler per event that calls `flushSync()`
|
|
144
175
|
* before the process terminates.
|
package/esm/logger.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logger.d.mts","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"logger.d.mts","names":[],"sources":["../../../../../../@warlock.js/logger/src/logger.ts"],"mappings":";;;;cAoCa,MAAA;;AAAb;;EAIS,QAAA,EAAU,UAAA;EAEV,EAAA;EA4BoB;;;;;EAAA,QArBnB,iBAAA;EA0EY;;;;;;EAAA,QAlEZ,QAAA;EAkLI;;;;;;EAAA,QA1KJ,YAAA;EAoMuB;;;EA/LxB,UAAA,CAAW,OAAA,EAAS,UAAA;EAsNX;;;EA7MT,SAAA,CAAU,MAAA;IACf,QAAA,GAAW,UAAA;IACX,WAAA,GAAc,cAAA;IACd,QAAA,GAAW,QAAA;IACX,MAAA,GAAS,YAAA;EAAA;EAsPU;;;;;;;;;;;EAtNd,SAAA,CAAU,MAAA,EAAQ,YAAA;EAzElB;;;EAiFA,SAAA,IAAa,YAAA;EArDb;;;;;;;;;;EAmEA,WAAA,CAAY,KAAA,EAAO,QAAA;EAtDf;;;EA8DJ,WAAA,IAAe,QAAA;EA9BL;;;EAqCV,WAAA,CAAY,QAAA,EAAU,UAAA;EAfH;;;EAAA,QAwBlB,gBAAA;EATD;;;;;;;;;EA4CM,GAAA,CAAI,IAAA,EAAM,WAAA,GAAW,OAAA;EAoChC;;;EADK,KAAA,CACL,YAAA,EAAc,kBAAA,WACd,MAAA,WACA,OAAA,QACA,OAAA,GAAU,MAAA,gBAAmB,OAAA;EAA7B;;;EASK,IAAA,CACL,YAAA,EAAc,kBAAA,WACd,MAAA,WACA,OAAA,QACA,OAAA,GAAU,MAAA,gBAAmB,OAAA;EAH7B;;;EAYK,IAAA,CACL,YAAA,EAAc,kBAAA,WACd,MAAA,WACA,OAAA,QACA,OAAA,GAAU,MAAA,gBAAmB,OAAA;EAb7B;;;EAsBK,KAAA,CACL,YAAA,EAAc,kBAAA,WACd,MAAA,WACA,OAAA,QACA,OAAA,GAAU,MAAA,gBAAmB,OAAA;EAhB7B;;;EAyBK,OAAA,CACL,YAAA,EAAc,kBAAA,WACd,MAAA,WACA,OAAA,QACA,OAAA,GAAU,MAAA,gBAAmB,OAAA;EA1B7B;;;;;;;;;EA0CK,KAAA,CACL,YAAA,EAAc,kBAAA,WACd,MAAA,WACA,OAAA,QACA,OAAA,GAAU,MAAA,gBAAmB,OAAA;EAxBxB;;;;;;;;;EAwCA,MAAA,CACL,SAAA,WACA,MAAA,UACA,MAAA,UACA,OAAA,OACA,OAAA,GAAU,MAAA,gBACT,OAAA,CAAQ,MAAA,IAAU,MAAA;EAzBnB;;;;;;;;;;EAwCK,KAAA,CACL,MAAA,UACA,MAAA,YACE,KAAA,GAAQ,MAAA,kBAAwB,OAAA,CAAQ,MAAA;EAnBhC;;;EAiCL,OAAA,CAAQ,IAAA,WAAY,UAAA,CAdgB,sBAAA;EAlBtB;;;EAuCd,SAAA;EArBK;;;;;;;;;;;;;;;;AA6GW;AAyBzB;;;EArFe,KAAA,IAAS,OAAA;EAqFO;;;;;;;;;;;;;;;;;;EAlDtB,eAAA,CAAgB,MAAA,EAAQ,cAAA;;;;;EAyBxB,gBAAA;AAAA;;;;;;;;;;;;;;;cAyBI,GAAA,EAAG,MAAe"}
|
package/esm/logger.mjs
CHANGED
|
@@ -2,7 +2,7 @@ import { applyRedact, mergeRedact } from "./redact/redact.mjs";
|
|
|
2
2
|
import { clearMessage } from "./utils/clear-message.mjs";
|
|
3
3
|
import { Random } from "@mongez/reinforcements";
|
|
4
4
|
|
|
5
|
-
//#region
|
|
5
|
+
//#region ../@warlock.js/logger/src/logger.ts
|
|
6
6
|
const SIGNAL_EVENTS = new Set([
|
|
7
7
|
"SIGINT",
|
|
8
8
|
"SIGTERM",
|
|
@@ -22,7 +22,8 @@ const LEVEL_RANK = {
|
|
|
22
22
|
info: 1,
|
|
23
23
|
success: 1,
|
|
24
24
|
warn: 2,
|
|
25
|
-
error: 3
|
|
25
|
+
error: 3,
|
|
26
|
+
fatal: 4
|
|
26
27
|
};
|
|
27
28
|
var Logger = class {
|
|
28
29
|
constructor() {
|
|
@@ -174,6 +175,19 @@ var Logger = class {
|
|
|
174
175
|
return this.log(data);
|
|
175
176
|
}
|
|
176
177
|
/**
|
|
178
|
+
* Make fatal log — for unrecoverable failures where the application is going
|
|
179
|
+
* down (failed bootstrap, lost connection to a required dependency that the
|
|
180
|
+
* caller has decided not to retry, an `uncaughtException`).
|
|
181
|
+
*
|
|
182
|
+
* Identical shape to {@link error}; the level is purely informational —
|
|
183
|
+
* `fatal` does NOT auto-flush or exit. The caller decides whether to call
|
|
184
|
+
* `await log.flush()` and `process.exit(...)`.
|
|
185
|
+
*/
|
|
186
|
+
fatal(dataOrModule, action, message = "", context) {
|
|
187
|
+
const data = this.normalizeLogData(dataOrModule, action, message, "fatal", context);
|
|
188
|
+
return this.log(data);
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
177
191
|
* Log an `error` entry when `condition` is falsy. No-op otherwise — the
|
|
178
192
|
* entry is never built and channels are not invoked, so this is genuinely
|
|
179
193
|
* free in the happy path. Mirrors the spirit of `console.assert` but routes
|
|
@@ -219,6 +233,34 @@ var Logger = class {
|
|
|
219
233
|
for (const channel of this.channels) if (channel.flushSync) channel.flushSync();
|
|
220
234
|
}
|
|
221
235
|
/**
|
|
236
|
+
* Asynchronously drain every channel that implements `flush()`.
|
|
237
|
+
*
|
|
238
|
+
* Unlike {@link flushSync}, this awaits each channel's async I/O — the
|
|
239
|
+
* correct call for a graceful shutdown that can afford to wait
|
|
240
|
+
* (`await log.flush()` after closing the HTTP server, before
|
|
241
|
+
* `process.exit`). A channel whose delivery is async (a network transport,
|
|
242
|
+
* an async disk write) implements `flush()`, not `flushSync()`.
|
|
243
|
+
*
|
|
244
|
+
* Channels are isolated: a channel whose flush rejects can neither prevent
|
|
245
|
+
* the others from draining nor escape as an unhandled rejection. Channels
|
|
246
|
+
* without `flush()` are skipped.
|
|
247
|
+
*
|
|
248
|
+
* @example
|
|
249
|
+
* async function shutdown() {
|
|
250
|
+
* await httpServer.close();
|
|
251
|
+
* await log.flush();
|
|
252
|
+
* process.exit(0);
|
|
253
|
+
* }
|
|
254
|
+
*/
|
|
255
|
+
async flush() {
|
|
256
|
+
await Promise.allSettled(this.channels.map(async (channel) => {
|
|
257
|
+
if (!channel.flush) return;
|
|
258
|
+
try {
|
|
259
|
+
await channel.flush();
|
|
260
|
+
} catch {}
|
|
261
|
+
}));
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
222
264
|
* Register one process-level handler per event that calls `flushSync()`
|
|
223
265
|
* before the process terminates.
|
|
224
266
|
*
|
package/esm/logger.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logger.mjs","names":[],"sources":["../../../../../@warlock.js/logger/src/logger.ts"],"sourcesContent":["import { Random } from \"@mongez/reinforcements\";\r\nimport type { LogChannel } from \"./log-channel\";\r\nimport { applyRedact, mergeRedact } from \"./redact\";\r\nimport type {\r\n AutoFlushEvent,\r\n LoggingData,\r\n LogLevel,\r\n OmittedLoggingData,\r\n RedactConfig,\r\n} from \"./types\";\r\nimport { clearMessage } from \"./utils/clear-message\";\r\n\r\nconst SIGNAL_EVENTS: ReadonlySet<AutoFlushEvent> = new Set([\r\n \"SIGINT\",\r\n \"SIGTERM\",\r\n \"SIGHUP\",\r\n \"SIGBREAK\",\r\n \"SIGUSR2\",\r\n]);\r\n\r\n/**\r\n * Severity ranks used by `setMinLevel`. Higher number = more severe. The\r\n * ordering matches conventional log-level hierarchies: `debug` is noisiest\r\n * and easiest to drop; `error` is the loudest and never dropped by the\r\n * minimum-level filter. `success` sits beside `info` — it's an informational\r\n * outcome, not a warning.\r\n */\r\nconst LEVEL_RANK: Record<LogLevel, number> = {\r\n debug: 0,\r\n info: 1,\r\n success: 1,\r\n warn: 2,\r\n error: 3,\r\n};\r\n\r\nexport class Logger {\r\n /**\r\n * Current channel\r\n */\r\n public channels: LogChannel[] = [];\r\n\r\n public id = \"logger-\" + Random.string(32);\r\n\r\n /**\r\n * Registered auto-flush handlers, keyed by event name. Stored so repeated\r\n * calls to `enableAutoFlush` replace rather than stack, and so\r\n * `disableAutoFlush` can remove them cleanly.\r\n */\r\n private autoFlushHandlers = new Map<AutoFlushEvent, () => void>();\r\n\r\n /**\r\n * Logger-wide minimum severity. When set, entries below this level are\r\n * dropped before any channel is invoked — cheaper than per-channel `levels`\r\n * filters because the fan-out loop is skipped entirely. `undefined` means\r\n * no minimum (every entry reaches every channel that accepts it).\r\n */\r\n private minLevel?: LogLevel;\r\n\r\n /**\r\n * Logger-wide redaction floor. Applied once before fan-out — every\r\n * channel receives an entry with these paths already censored. Channel\r\n * configs can extend the path list (additive); they cannot remove paths\r\n * set here.\r\n */\r\n private redactConfig?: RedactConfig;\r\n\r\n /**\r\n * Add a new channel\r\n */\r\n public addChannel(channel: LogChannel) {\r\n this.channels.push(channel);\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Set base configurations\r\n */\r\n public configure(config: {\r\n channels?: LogChannel[];\r\n autoFlushOn?: AutoFlushEvent[];\r\n minLevel?: LogLevel;\r\n redact?: RedactConfig;\r\n }) {\r\n if (config.channels) {\r\n this.channels = config.channels;\r\n }\r\n\r\n if (config.autoFlushOn) {\r\n this.enableAutoFlush(config.autoFlushOn);\r\n }\r\n\r\n if (config.minLevel !== undefined) {\r\n this.setMinLevel(config.minLevel);\r\n }\r\n\r\n if (config.redact !== undefined) {\r\n this.setRedact(config.redact);\r\n }\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Set the logger-wide redaction floor. Applied to every entry before\r\n * fan-out; channel configs add more paths on top, never fewer. Pass\r\n * `undefined` to clear.\r\n *\r\n * @example\r\n * log.setRedact({\r\n * paths: [\"context.password\", \"context.*.token\"],\r\n * censor: \"[REDACTED]\",\r\n * });\r\n */\r\n public setRedact(config: RedactConfig | undefined): this {\r\n this.redactConfig = config;\r\n return this;\r\n }\r\n\r\n /**\r\n * Read the active logger-wide redact config (or `undefined`).\r\n */\r\n public getRedact(): RedactConfig | undefined {\r\n return this.redactConfig;\r\n }\r\n\r\n /**\r\n * Drop every entry whose severity is below `level` before fan-out. Cheaper\r\n * than per-channel `levels` filters because the loop never runs and no\r\n * channel receives the entry. Pass `undefined` to clear and accept all\r\n * levels again.\r\n *\r\n * @example\r\n * // production: silence debug noise everywhere at once\r\n * logger.setMinLevel(\"info\");\r\n */\r\n public setMinLevel(level: LogLevel | undefined): this {\r\n this.minLevel = level;\r\n return this;\r\n }\r\n\r\n /**\r\n * Read the active minimum severity (or `undefined` when none is set).\r\n */\r\n public getMinLevel(): LogLevel | undefined {\r\n return this.minLevel;\r\n }\r\n\r\n /**\r\n * Set channels\r\n */\r\n public setChannels(channels: LogChannel[]) {\r\n this.channels = channels;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Normalize log data to a single object\r\n */\r\n private normalizeLogData(\r\n dataOrModule: LoggingData | OmittedLoggingData | string,\r\n action?: string,\r\n message: any = \"\",\r\n level?: LogLevel,\r\n context?: Record<string, any>,\r\n ): LoggingData {\r\n if (typeof dataOrModule === \"object\") {\r\n // If level is provided, override type\r\n return {\r\n type: (level || (dataOrModule as any).type || \"info\") as LogLevel,\r\n module: dataOrModule.module,\r\n action: dataOrModule.action,\r\n message: dataOrModule.message,\r\n ...(context ? { context } : dataOrModule.context ? { context: dataOrModule.context } : {}),\r\n };\r\n }\r\n return {\r\n type: (level || \"info\") as LogLevel,\r\n module: dataOrModule,\r\n action: action as string,\r\n message,\r\n ...(context ? { context } : {}),\r\n };\r\n }\r\n\r\n /**\r\n * Make log\r\n *\r\n * Fans out a single log entry to every registered channel. Non-terminal\r\n * channels receive a copy whose `message` has had ANSI color codes stripped\r\n * — each channel sees its own shallow clone so one channel cannot observe\r\n * another's mutations (e.g. a later terminal channel still sees the original\r\n * colored message).\r\n */\r\n public async log(data: LoggingData) {\r\n if (this.minLevel && LEVEL_RANK[data.type] < LEVEL_RANK[this.minLevel]) {\r\n return this;\r\n }\r\n\r\n // Apply the logger-wide redact floor once. Every channel sees the\r\n // result; no channel can undo a logger-wide redaction (additive-only\r\n // semantics).\r\n const baseEntry = applyRedact(data, this.redactConfig);\r\n\r\n for (const channel of this.channels) {\r\n const channelRedact = channel.getRedactConfig?.();\r\n const effectiveRedact = channelRedact\r\n ? mergeRedact(this.redactConfig, channelRedact)\r\n : undefined;\r\n\r\n // When the channel adds paths, redact again from `data` rather than\r\n // from `baseEntry` so the merged config (which already contains the\r\n // logger-wide paths) does the full pass — avoids double-cloning the\r\n // already-redacted base.\r\n let payload = effectiveRedact ? applyRedact(data, effectiveRedact) : baseEntry;\r\n\r\n if (channel.terminal === false) {\r\n payload = { ...payload, message: clearMessage(payload.message) };\r\n }\r\n\r\n channel.log(payload);\r\n }\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Make debug log\r\n */\r\n public debug(\r\n dataOrModule: OmittedLoggingData | string,\r\n action?: string,\r\n message: any = \"\",\r\n context?: Record<string, any>,\r\n ) {\r\n const data = this.normalizeLogData(dataOrModule, action, message, \"debug\", context);\r\n return this.log(data);\r\n }\r\n\r\n /**\r\n * Make info log\r\n */\r\n public info(\r\n dataOrModule: OmittedLoggingData | string,\r\n action?: string,\r\n message: any = \"\",\r\n context?: Record<string, any>,\r\n ) {\r\n const data = this.normalizeLogData(dataOrModule, action, message, \"info\", context);\r\n return this.log(data);\r\n }\r\n\r\n /**\r\n * Make warn log\r\n */\r\n public warn(\r\n dataOrModule: OmittedLoggingData | string,\r\n action?: string,\r\n message: any = \"\",\r\n context?: Record<string, any>,\r\n ) {\r\n const data = this.normalizeLogData(dataOrModule, action, message, \"warn\", context);\r\n return this.log(data);\r\n }\r\n\r\n /**\r\n * Make error log\r\n */\r\n public error(\r\n dataOrModule: OmittedLoggingData | string,\r\n action?: string,\r\n message: any = \"\",\r\n context?: Record<string, any>,\r\n ) {\r\n const data = this.normalizeLogData(dataOrModule, action, message, \"error\", context);\r\n return this.log(data);\r\n }\r\n\r\n /**\r\n * Make success log\r\n */\r\n public success(\r\n dataOrModule: OmittedLoggingData | string,\r\n action?: string,\r\n message: any = \"\",\r\n context?: Record<string, any>,\r\n ) {\r\n const data = this.normalizeLogData(dataOrModule, action, message, \"success\", context);\r\n\r\n return this.log(data);\r\n }\r\n\r\n /**\r\n * Log an `error` entry when `condition` is falsy. No-op otherwise — the\r\n * entry is never built and channels are not invoked, so this is genuinely\r\n * free in the happy path. Mirrors the spirit of `console.assert` but routes\r\n * through the logger pipeline so persistent channels capture failures.\r\n *\r\n * @example\r\n * log.assert(user !== null, \"auth\", \"session\", \"user vanished mid-flight\", { sessionId });\r\n */\r\n public assert(\r\n condition: unknown,\r\n module: string,\r\n action: string,\r\n message: any,\r\n context?: Record<string, any>,\r\n ): Promise<Logger> | Logger {\r\n if (condition) return this;\r\n return this.error(module, action, message, context);\r\n }\r\n\r\n /**\r\n * Start a duration timer. The returned function emits an `info` entry\r\n * with `completed in <ms>ms` and a `durationMs` field in `context` when\r\n * called. Pass an object to `end()` to merge extra fields into context.\r\n *\r\n * @example\r\n * const end = log.timer(\"db\", \"users.findById\");\r\n * const user = await usersRepo.findById(id);\r\n * end({ id, found: !!user });\r\n */\r\n public timer(\r\n module: string,\r\n action: string,\r\n ): (extra?: Record<string, any>) => Promise<Logger> {\r\n const startedAt = Date.now();\r\n return (extra?: Record<string, any>) => {\r\n const durationMs = Date.now() - startedAt;\r\n return this.info(module, action, `completed in ${durationMs}ms`, {\r\n durationMs,\r\n ...(extra ?? {}),\r\n });\r\n };\r\n }\r\n\r\n /**\r\n * Get channel by name\r\n */\r\n public channel(name: string) {\r\n return this.channels.find((channel) => channel.name === name);\r\n }\r\n\r\n /**\r\n * Synchronously flush logs\r\n */\r\n public flushSync() {\r\n for (const channel of this.channels) {\r\n if (channel.flushSync) {\r\n channel.flushSync();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Register one process-level handler per event that calls `flushSync()`\r\n * before the process terminates.\r\n *\r\n * For signal events (`SIGINT`, `SIGTERM`, `SIGHUP`, `SIGBREAK`, `SIGUSR2`)\r\n * the handler flushes and then re-raises the signal so Node's default exit\r\n * behavior runs. For `beforeExit`, the handler flushes in place — Node exits\r\n * naturally afterwards.\r\n *\r\n * Idempotent: calling with the same events replaces the previous handlers.\r\n * Call `disableAutoFlush()` to unregister.\r\n *\r\n * @example\r\n * log.configure({\r\n * channels: [new ConsoleLog(), new FileLog()],\r\n * autoFlushOn: [\"SIGINT\", \"SIGTERM\", \"beforeExit\"],\r\n * });\r\n */\r\n public enableAutoFlush(events: AutoFlushEvent[]): this {\r\n this.disableAutoFlush();\r\n\r\n for (const event of events) {\r\n const handler = SIGNAL_EVENTS.has(event)\r\n ? () => {\r\n this.flushSync();\r\n process.off(event, handler);\r\n process.kill(process.pid, event as NodeJS.Signals);\r\n }\r\n : () => {\r\n this.flushSync();\r\n };\r\n\r\n process.on(event, handler);\r\n this.autoFlushHandlers.set(event, handler);\r\n }\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Remove every handler previously registered by `enableAutoFlush`.\r\n * Safe to call when no handlers are registered.\r\n */\r\n public disableAutoFlush(): this {\r\n for (const [event, handler] of this.autoFlushHandlers) {\r\n process.off(event, handler);\r\n }\r\n\r\n this.autoFlushHandlers.clear();\r\n\r\n return this;\r\n }\r\n}\r\n\r\n/**\r\n * The package singleton. Use this for everyday logging — `log.info(...)`,\r\n * `log.error(...)`, `log.configure(...)`. Custom logger instances can be\r\n * created by instantiating `Logger` directly.\r\n *\r\n * The name is intentionally short: `log` reads naturally at the call site\r\n * (`log.info(\"auth\", \"login\", \"ok\")`) and matches the convention used in\r\n * pino, bunyan, and most JS logging tutorials.\r\n *\r\n * Note that `log` is a `Logger` instance, **not** a function — the bare\r\n * callable form was removed when the dual `log` / `logger` exports were\r\n * collapsed into a single name. Use `log.info(...)` (or any other level\r\n * shortcut) to emit entries.\r\n */\r\nexport const log = new Logger();\r\n"],"mappings":";;;;;AAYA,MAAM,gBAA6C,IAAI,IAAI;CACzD;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;;;AASD,MAAM,aAAuC;CAC3C,OAAO;CACP,MAAM;CACN,SAAS;CACT,MAAM;CACN,OAAO;AACT;AAEA,IAAa,SAAb,MAAoB;;kBAIc,CAAC;YAErB,YAAY,OAAO,OAAO,EAAE;2CAOZ,IAAI,IAAgC;;;;;CAqBhE,AAAO,WAAW,SAAqB;EACrC,KAAK,SAAS,KAAK,OAAO;EAE1B,OAAO;CACT;;;;CAKA,AAAO,UAAU,QAKd;EACD,IAAI,OAAO,UACT,KAAK,WAAW,OAAO;EAGzB,IAAI,OAAO,aACT,KAAK,gBAAgB,OAAO,WAAW;EAGzC,IAAI,OAAO,aAAa,QACtB,KAAK,YAAY,OAAO,QAAQ;EAGlC,IAAI,OAAO,WAAW,QACpB,KAAK,UAAU,OAAO,MAAM;EAG9B,OAAO;CACT;;;;;;;;;;;;CAaA,AAAO,UAAU,QAAwC;EACvD,KAAK,eAAe;EACpB,OAAO;CACT;;;;CAKA,AAAO,YAAsC;EAC3C,OAAO,KAAK;CACd;;;;;;;;;;;CAYA,AAAO,YAAY,OAAmC;EACpD,KAAK,WAAW;EAChB,OAAO;CACT;;;;CAKA,AAAO,cAAoC;EACzC,OAAO,KAAK;CACd;;;;CAKA,AAAO,YAAY,UAAwB;EACzC,KAAK,WAAW;EAEhB,OAAO;CACT;;;;CAKA,AAAQ,iBACN,cACA,QACA,UAAe,IACf,OACA,SACa;EACb,IAAI,OAAO,iBAAiB,UAE1B,OAAO;GACL,MAAO,SAAU,aAAqB,QAAQ;GAC9C,QA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OAAO;EAG5B,KAAK,kBAAkB,MAAM;EAE7B,OAAO;CACT;AACF;;;;;;;;;;;;;;;AAgBA,MAAa,MAAM,IAAI,OAAO"}
|
|
1
|
+
{"version":3,"file":"logger.mjs","names":[],"sources":["../../../../../../@warlock.js/logger/src/logger.ts"],"sourcesContent":["import { Random } from \"@mongez/reinforcements\";\r\nimport type { LogChannel } from \"./log-channel\";\r\nimport { applyRedact, mergeRedact } from \"./redact\";\r\nimport type {\r\n AutoFlushEvent,\r\n LoggingData,\r\n LogLevel,\r\n OmittedLoggingData,\r\n RedactConfig,\r\n} from \"./types\";\r\nimport { clearMessage } from \"./utils/clear-message\";\r\n\r\nconst SIGNAL_EVENTS: ReadonlySet<AutoFlushEvent> = new Set([\r\n \"SIGINT\",\r\n \"SIGTERM\",\r\n \"SIGHUP\",\r\n \"SIGBREAK\",\r\n \"SIGUSR2\",\r\n]);\r\n\r\n/**\r\n * Severity ranks used by `setMinLevel`. Higher number = more severe. The\r\n * ordering matches conventional log-level hierarchies: `debug` is noisiest\r\n * and easiest to drop; `error` is the loudest and never dropped by the\r\n * minimum-level filter. `success` sits beside `info` — it's an informational\r\n * outcome, not a warning.\r\n */\r\nconst LEVEL_RANK: Record<LogLevel, number> = {\r\n debug: 0,\r\n info: 1,\r\n success: 1,\r\n warn: 2,\r\n error: 3,\r\n fatal: 4,\r\n};\r\n\r\nexport class Logger {\r\n /**\r\n * Current channel\r\n */\r\n public channels: LogChannel[] = [];\r\n\r\n public id = \"logger-\" + Random.string(32);\r\n\r\n /**\r\n * Registered auto-flush handlers, keyed by event name. Stored so repeated\r\n * calls to `enableAutoFlush` replace rather than stack, and so\r\n * `disableAutoFlush` can remove them cleanly.\r\n */\r\n private autoFlushHandlers = new Map<AutoFlushEvent, () => void>();\r\n\r\n /**\r\n * Logger-wide minimum severity. When set, entries below this level are\r\n * dropped before any channel is invoked — cheaper than per-channel `levels`\r\n * filters because the fan-out loop is skipped entirely. `undefined` means\r\n * no minimum (every entry reaches every channel that accepts it).\r\n */\r\n private minLevel?: LogLevel;\r\n\r\n /**\r\n * Logger-wide redaction floor. Applied once before fan-out — every\r\n * channel receives an entry with these paths already censored. Channel\r\n * configs can extend the path list (additive); they cannot remove paths\r\n * set here.\r\n */\r\n private redactConfig?: RedactConfig;\r\n\r\n /**\r\n * Add a new channel\r\n */\r\n public addChannel(channel: LogChannel) {\r\n this.channels.push(channel);\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Set base configurations\r\n */\r\n public configure(config: {\r\n channels?: LogChannel[];\r\n autoFlushOn?: AutoFlushEvent[];\r\n minLevel?: LogLevel;\r\n redact?: RedactConfig;\r\n }) {\r\n if (config.channels) {\r\n this.channels = config.channels;\r\n }\r\n\r\n if (config.autoFlushOn) {\r\n this.enableAutoFlush(config.autoFlushOn);\r\n }\r\n\r\n if (config.minLevel !== undefined) {\r\n this.setMinLevel(config.minLevel);\r\n }\r\n\r\n if (config.redact !== undefined) {\r\n this.setRedact(config.redact);\r\n }\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Set the logger-wide redaction floor. Applied to every entry before\r\n * fan-out; channel configs add more paths on top, never fewer. Pass\r\n * `undefined` to clear.\r\n *\r\n * @example\r\n * log.setRedact({\r\n * paths: [\"context.password\", \"context.*.token\"],\r\n * censor: \"[REDACTED]\",\r\n * });\r\n */\r\n public setRedact(config: RedactConfig | undefined): this {\r\n this.redactConfig = config;\r\n return this;\r\n }\r\n\r\n /**\r\n * Read the active logger-wide redact config (or `undefined`).\r\n */\r\n public getRedact(): RedactConfig | undefined {\r\n return this.redactConfig;\r\n }\r\n\r\n /**\r\n * Drop every entry whose severity is below `level` before fan-out. Cheaper\r\n * than per-channel `levels` filters because the loop never runs and no\r\n * channel receives the entry. Pass `undefined` to clear and accept all\r\n * levels again.\r\n *\r\n * @example\r\n * // production: silence debug noise everywhere at once\r\n * logger.setMinLevel(\"info\");\r\n */\r\n public setMinLevel(level: LogLevel | undefined): this {\r\n this.minLevel = level;\r\n return this;\r\n }\r\n\r\n /**\r\n * Read the active minimum severity (or `undefined` when none is set).\r\n */\r\n public getMinLevel(): LogLevel | undefined {\r\n return this.minLevel;\r\n }\r\n\r\n /**\r\n * Set channels\r\n */\r\n public setChannels(channels: LogChannel[]) {\r\n this.channels = channels;\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Normalize log data to a single object\r\n */\r\n private normalizeLogData(\r\n dataOrModule: LoggingData | OmittedLoggingData | string,\r\n action?: string,\r\n message: any = \"\",\r\n level?: LogLevel,\r\n context?: Record<string, any>,\r\n ): LoggingData {\r\n if (typeof dataOrModule === \"object\") {\r\n // If level is provided, override type\r\n return {\r\n type: (level || (dataOrModule as any).type || \"info\") as LogLevel,\r\n module: dataOrModule.module,\r\n action: dataOrModule.action,\r\n message: dataOrModule.message,\r\n ...(context ? { context } : dataOrModule.context ? { context: dataOrModule.context } : {}),\r\n };\r\n }\r\n return {\r\n type: (level || \"info\") as LogLevel,\r\n module: dataOrModule,\r\n action: action as string,\r\n message,\r\n ...(context ? { context } : {}),\r\n };\r\n }\r\n\r\n /**\r\n * Make log\r\n *\r\n * Fans out a single log entry to every registered channel. Non-terminal\r\n * channels receive a copy whose `message` has had ANSI color codes stripped\r\n * — each channel sees its own shallow clone so one channel cannot observe\r\n * another's mutations (e.g. a later terminal channel still sees the original\r\n * colored message).\r\n */\r\n public async log(data: LoggingData) {\r\n if (this.minLevel && LEVEL_RANK[data.type] < LEVEL_RANK[this.minLevel]) {\r\n return this;\r\n }\r\n\r\n // Apply the logger-wide redact floor once. Every channel sees the\r\n // result; no channel can undo a logger-wide redaction (additive-only\r\n // semantics).\r\n const baseEntry = applyRedact(data, this.redactConfig);\r\n\r\n for (const channel of this.channels) {\r\n const channelRedact = channel.getRedactConfig?.();\r\n const effectiveRedact = channelRedact\r\n ? mergeRedact(this.redactConfig, channelRedact)\r\n : undefined;\r\n\r\n // When the channel adds paths, redact again from `data` rather than\r\n // from `baseEntry` so the merged config (which already contains the\r\n // logger-wide paths) does the full pass — avoids double-cloning the\r\n // already-redacted base.\r\n let payload = effectiveRedact ? applyRedact(data, effectiveRedact) : baseEntry;\r\n\r\n if (channel.terminal === false) {\r\n payload = { ...payload, message: clearMessage(payload.message) };\r\n }\r\n\r\n channel.log(payload);\r\n }\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Make debug log\r\n */\r\n public debug(\r\n dataOrModule: OmittedLoggingData | string,\r\n action?: string,\r\n message: any = \"\",\r\n context?: Record<string, any>,\r\n ) {\r\n const data = this.normalizeLogData(dataOrModule, action, message, \"debug\", context);\r\n return this.log(data);\r\n }\r\n\r\n /**\r\n * Make info log\r\n */\r\n public info(\r\n dataOrModule: OmittedLoggingData | string,\r\n action?: string,\r\n message: any = \"\",\r\n context?: Record<string, any>,\r\n ) {\r\n const data = this.normalizeLogData(dataOrModule, action, message, \"info\", context);\r\n return this.log(data);\r\n }\r\n\r\n /**\r\n * Make warn log\r\n */\r\n public warn(\r\n dataOrModule: OmittedLoggingData | string,\r\n action?: string,\r\n message: any = \"\",\r\n context?: Record<string, any>,\r\n ) {\r\n const data = this.normalizeLogData(dataOrModule, action, message, \"warn\", context);\r\n return this.log(data);\r\n }\r\n\r\n /**\r\n * Make error log\r\n */\r\n public error(\r\n dataOrModule: OmittedLoggingData | string,\r\n action?: string,\r\n message: any = \"\",\r\n context?: Record<string, any>,\r\n ) {\r\n const data = this.normalizeLogData(dataOrModule, action, message, \"error\", context);\r\n return this.log(data);\r\n }\r\n\r\n /**\r\n * Make success log\r\n */\r\n public success(\r\n dataOrModule: OmittedLoggingData | string,\r\n action?: string,\r\n message: any = \"\",\r\n context?: Record<string, any>,\r\n ) {\r\n const data = this.normalizeLogData(dataOrModule, action, message, \"success\", context);\r\n\r\n return this.log(data);\r\n }\r\n\r\n /**\r\n * Make fatal log — for unrecoverable failures where the application is going\r\n * down (failed bootstrap, lost connection to a required dependency that the\r\n * caller has decided not to retry, an `uncaughtException`).\r\n *\r\n * Identical shape to {@link error}; the level is purely informational —\r\n * `fatal` does NOT auto-flush or exit. The caller decides whether to call\r\n * `await log.flush()` and `process.exit(...)`.\r\n */\r\n public fatal(\r\n dataOrModule: OmittedLoggingData | string,\r\n action?: string,\r\n message: any = \"\",\r\n context?: Record<string, any>,\r\n ) {\r\n const data = this.normalizeLogData(dataOrModule, action, message, \"fatal\", context);\r\n\r\n return this.log(data);\r\n }\r\n\r\n /**\r\n * Log an `error` entry when `condition` is falsy. No-op otherwise — the\r\n * entry is never built and channels are not invoked, so this is genuinely\r\n * free in the happy path. Mirrors the spirit of `console.assert` but routes\r\n * through the logger pipeline so persistent channels capture failures.\r\n *\r\n * @example\r\n * log.assert(user !== null, \"auth\", \"session\", \"user vanished mid-flight\", { sessionId });\r\n */\r\n public assert(\r\n condition: unknown,\r\n module: string,\r\n action: string,\r\n message: any,\r\n context?: Record<string, any>,\r\n ): Promise<Logger> | Logger {\r\n if (condition) return this;\r\n return this.error(module, action, message, context);\r\n }\r\n\r\n /**\r\n * Start a duration timer. The returned function emits an `info` entry\r\n * with `completed in <ms>ms` and a `durationMs` field in `context` when\r\n * called. Pass an object to `end()` to merge extra fields into context.\r\n *\r\n * @example\r\n * const end = log.timer(\"db\", \"users.findById\");\r\n * const user = await usersRepo.findById(id);\r\n * end({ id, found: !!user });\r\n */\r\n public timer(\r\n module: string,\r\n action: string,\r\n ): (extra?: Record<string, any>) => Promise<Logger> {\r\n const startedAt = Date.now();\r\n return (extra?: Record<string, any>) => {\r\n const durationMs = Date.now() - startedAt;\r\n return this.info(module, action, `completed in ${durationMs}ms`, {\r\n durationMs,\r\n ...(extra ?? {}),\r\n });\r\n };\r\n }\r\n\r\n /**\r\n * Get channel by name\r\n */\r\n public channel(name: string) {\r\n return this.channels.find((channel) => channel.name === name);\r\n }\r\n\r\n /**\r\n * Synchronously flush logs\r\n */\r\n public flushSync() {\r\n for (const channel of this.channels) {\r\n if (channel.flushSync) {\r\n channel.flushSync();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Asynchronously drain every channel that implements `flush()`.\r\n *\r\n * Unlike {@link flushSync}, this awaits each channel's async I/O — the\r\n * correct call for a graceful shutdown that can afford to wait\r\n * (`await log.flush()` after closing the HTTP server, before\r\n * `process.exit`). A channel whose delivery is async (a network transport,\r\n * an async disk write) implements `flush()`, not `flushSync()`.\r\n *\r\n * Channels are isolated: a channel whose flush rejects can neither prevent\r\n * the others from draining nor escape as an unhandled rejection. Channels\r\n * without `flush()` are skipped.\r\n *\r\n * @example\r\n * async function shutdown() {\r\n * await httpServer.close();\r\n * await log.flush();\r\n * process.exit(0);\r\n * }\r\n */\r\n public async flush(): Promise<void> {\r\n await Promise.allSettled(\r\n this.channels.map(async (channel) => {\r\n if (!channel.flush) {\r\n return;\r\n }\r\n\r\n try {\r\n await channel.flush();\r\n } catch {\r\n // A single channel must never break shutdown for the others —\r\n // a graceful drain is best-effort across every channel.\r\n }\r\n }),\r\n );\r\n }\r\n\r\n /**\r\n * Register one process-level handler per event that calls `flushSync()`\r\n * before the process terminates.\r\n *\r\n * For signal events (`SIGINT`, `SIGTERM`, `SIGHUP`, `SIGBREAK`, `SIGUSR2`)\r\n * the handler flushes and then re-raises the signal so Node's default exit\r\n * behavior runs. For `beforeExit`, the handler flushes in place — Node exits\r\n * naturally afterwards.\r\n *\r\n * Idempotent: calling with the same events replaces the previous handlers.\r\n * Call `disableAutoFlush()` to unregister.\r\n *\r\n * @example\r\n * log.configure({\r\n * channels: [new ConsoleLog(), new FileLog()],\r\n * autoFlushOn: [\"SIGINT\", \"SIGTERM\", \"beforeExit\"],\r\n * });\r\n */\r\n public enableAutoFlush(events: AutoFlushEvent[]): this {\r\n this.disableAutoFlush();\r\n\r\n for (const event of events) {\r\n const handler = SIGNAL_EVENTS.has(event)\r\n ? () => {\r\n this.flushSync();\r\n process.off(event, handler);\r\n process.kill(process.pid, event as NodeJS.Signals);\r\n }\r\n : () => {\r\n this.flushSync();\r\n };\r\n\r\n process.on(event, handler);\r\n this.autoFlushHandlers.set(event, handler);\r\n }\r\n\r\n return this;\r\n }\r\n\r\n /**\r\n * Remove every handler previously registered by `enableAutoFlush`.\r\n * Safe to call when no handlers are registered.\r\n */\r\n public disableAutoFlush(): this {\r\n for (const [event, handler] of this.autoFlushHandlers) {\r\n process.off(event, handler);\r\n }\r\n\r\n this.autoFlushHandlers.clear();\r\n\r\n return this;\r\n }\r\n}\r\n\r\n/**\r\n * The package singleton. Use this for everyday logging — `log.info(...)`,\r\n * `log.error(...)`, `log.configure(...)`. Custom logger instances can be\r\n * created by instantiating `Logger` directly.\r\n *\r\n * The name is intentionally short: `log` reads naturally at the call site\r\n * (`log.info(\"auth\", \"login\", \"ok\")`) and matches the convention used in\r\n * pino, bunyan, and most JS logging tutorials.\r\n *\r\n * Note that `log` is a `Logger` instance, **not** a function — the bare\r\n * callable form was removed when the dual `log` / `logger` exports were\r\n * collapsed into a single name. Use `log.info(...)` (or any other level\r\n * shortcut) to emit entries.\r\n */\r\nexport const log = new Logger();\r\n"],"mappings":";;;;;AAYA,MAAM,gBAA6C,IAAI,IAAI;CACzD;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;;;AASD,MAAM,aAAuC;CAC3C,OAAO;CACP,MAAM;CACN,SAAS;CACT,MAAM;CACN,OAAO;CACP,OAAO;AACT;AAEA,IAAa,SAAb,MAAoB;;kBAIc,CAAC;YAErB,YAAY,OAAO,OAAO,EAAE;2CAOZ,IAAI,IAAgC;;;;;CAqBhE,AAAO,WAAW,SAAqB;EACrC,KAAK,SAAS,KAAK,OAAO;EAE1B,OAAO;CACT;;;;CAKA,AAAO,UAAU,QAKd;EACD,IAAI,OAAO,UACT,KAAK,WAAW,OAAO;EAGzB,IAAI,OAAO,aACT,KAAK,gBAAgB,OAAO,WAAW;EAGzC,IAAI,OAAO,aAAa,QACtB,KAAK,YAAY,OAAO,QAAQ;EAGlC,IAAI,OAAO,WAAW,QACpB,KAAK,UAAU,OAAO,MAAM;EAG9B,OAAO;CACT;;;;;;;;;;;;CAaA,AAAO,UAAU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;;CAKA,AAAO,YAAY;EACjB,KAAK,MAAM,WAAW,KAAK,UACzB,IAAI,QAAQ,WACV,QAAQ,UAAU;CAGxB;;;;;;;;;;;;;;;;;;;;;CAsBA,MAAa,QAAuB;EAClC,MAAM,QAAQ,WACZ,KAAK,SAAS,IAAI,OAAO,YAAY;GACnC,IAAI,CAAC,QAAQ,OACX;GAGF,IAAI;IACF,MAAM,QAAQ,MAAM;GACtB,QAAQ,CAGR;EACF,CAAC,CACH;CACF;;;;;;;;;;;;;;;;;;;CAoBA,AAAO,gBAAgB,QAAgC;EACrD,KAAK,iBAAiB;EAEtB,KAAK,MAAM,SAAS,QAAQ;GAC1B,MAAM,UAAU,cAAc,IAAI,KAAK,UAC7B;IACJ,KAAK,UAAU;IACf,QAAQ,IAAI,OAAO,OAAO;IAC1B,QAAQ,KAAK,QAAQ,KAAK,KAAuB;GACnD,UACM;IACJ,KAAK,UAAU;GACjB;GAEJ,QAAQ,GAAG,OAAO,OAAO;GACzB,KAAK,kBAAkB,IAAI,OAAO,OAAO;EAC3C;EAEA,OAAO;CACT;;;;;CAMA,AAAO,mBAAyB;EAC9B,KAAK,MAAM,CAAC,OAAO,YAAY,KAAK,mBAClC,QAAQ,IAAI,OAAO,OAAO;EAG5B,KAAK,kBAAkB,MAAM;EAE7B,OAAO;CACT;AACF;;;;;;;;;;;;;;;AAgBA,MAAa,MAAM,IAAI,OAAO"}
|
package/esm/redact/redact.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { LoggingData, RedactConfig } from "../types.mjs";
|
|
2
2
|
|
|
3
|
-
//#region
|
|
3
|
+
//#region ../@warlock.js/logger/src/redact/redact.d.ts
|
|
4
4
|
/**
|
|
5
5
|
* Produce a new `LoggingData` with every path in `config.paths` replaced
|
|
6
6
|
* by `config.censor`. The original entry is never mutated — channels and
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"redact.d.mts","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"redact.d.mts","names":[],"sources":["../../../../../../../@warlock.js/logger/src/redact/redact.ts"],"mappings":";;;;;AAyIA;;;;;;iBAAgB,WAAA,CACd,IAAA,EAAM,WAAA,EACN,MAAA,EAAQ,YAAA,eACP,WAAA;;;;;;;;AAAW;AA0Bd;iBAAgB,WAAA,CACd,IAAA,EAAM,YAAA,cACN,KAAA,EAAO,YAAA,eACN,YAAA"}
|
package/esm/redact/redact.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//#region
|
|
1
|
+
//#region ../@warlock.js/logger/src/redact/redact.ts
|
|
2
2
|
/**
|
|
3
3
|
* Deep-clone a value with structural fidelity for log entries — handles plain
|
|
4
4
|
* objects, arrays, `Date`, `Error`, and primitives. Anything else is copied
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"redact.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"redact.mjs","names":[],"sources":["../../../../../../../@warlock.js/logger/src/redact/redact.ts"],"sourcesContent":["import type { LoggingData, RedactCensor, RedactConfig } from \"../types\";\n\n/**\n * Deep-clone a value with structural fidelity for log entries — handles plain\n * objects, arrays, `Date`, `Error`, and primitives. Anything else is copied\n * by reference (we only redact paths through plain objects/arrays anyway,\n * and rebuilding e.g. a `Buffer` would change semantics).\n *\n * Purpose-built rather than reaching for `structuredClone`: `Error` instances\n * lose their `message`/`stack` under `structuredClone` in some Node versions,\n * and the logger pipeline carries them often.\n */\nfunction cloneEntry<T>(value: T, seen = new WeakMap<object, any>()): T {\n if (value === null || typeof value !== \"object\") {\n return value;\n }\n\n if (seen.has(value as unknown as object)) {\n return seen.get(value as unknown as object);\n }\n\n if (value instanceof Date) {\n return new Date(value.getTime()) as unknown as T;\n }\n\n if (value instanceof Error) {\n const copy = new (value.constructor as ErrorConstructor)(value.message);\n copy.stack = value.stack;\n copy.name = value.name;\n return copy as unknown as T;\n }\n\n if (Array.isArray(value)) {\n const arr: any[] = [];\n seen.set(value as unknown as object, arr);\n for (const item of value) {\n arr.push(cloneEntry(item, seen));\n }\n return arr as unknown as T;\n }\n\n const out: Record<string, any> = {};\n seen.set(value as unknown as object, out);\n for (const key of Object.keys(value as Record<string, any>)) {\n out[key] = cloneEntry((value as Record<string, any>)[key], seen);\n }\n return out as unknown as T;\n}\n\n/**\n * Apply a single censor decision to a value. String censors are returned\n * verbatim; function censors receive the original value plus the dotted\n * path so callers can implement value-aware redaction (mask all but the\n * last 4 chars, hash, etc.).\n */\nfunction applyCensor(value: any, censor: RedactCensor, path: string[]): any {\n if (typeof censor === \"function\") {\n return censor(value, path.join(\".\"));\n }\n return censor;\n}\n\n/**\n * Walk `target` following the remaining `segments` of a path pattern,\n * replacing matched leaves via `censor`. Operates in place — the caller\n * is responsible for cloning before calling.\n *\n * Wildcards:\n * - `*` matches exactly one segment (any key on a plain object, any index\n * on an array — stringified for the path that's passed to a function\n * censor).\n * - `**` matches zero or more segments greedily; the rest of the pattern\n * is then attempted at the current level and at every descendant.\n */\nfunction redactAtPath(\n target: any,\n segments: string[],\n censor: RedactCensor,\n pathTrail: string[],\n): void {\n if (target === null || typeof target !== \"object\") {\n return;\n }\n\n if (segments.length === 0) {\n return;\n }\n\n const [head, ...rest] = segments;\n\n if (head === \"**\") {\n // Try matching `rest` at the current level (the zero-segment match\n // case), then recurse into every child carrying the `**` forward so\n // it keeps matching at deeper levels too.\n if (rest.length > 0) {\n redactAtPath(target, rest, censor, pathTrail);\n }\n const keys = Array.isArray(target)\n ? target.map((_, index) => String(index))\n : Object.keys(target);\n for (const key of keys) {\n redactAtPath(target[key], segments, censor, [...pathTrail, key]);\n }\n return;\n }\n\n const keysToVisit =\n head === \"*\"\n ? Array.isArray(target)\n ? target.map((_, index) => String(index))\n : Object.keys(target)\n : Array.isArray(target)\n ? // Numeric segment can index into an array.\n /^\\d+$/.test(head) && Number(head) < target.length\n ? [head]\n : []\n : Object.prototype.hasOwnProperty.call(target, head)\n ? [head]\n : [];\n\n for (const key of keysToVisit) {\n if (rest.length === 0) {\n target[key] = applyCensor(target[key], censor, [...pathTrail, key]);\n } else {\n redactAtPath(target[key], rest, censor, [...pathTrail, key]);\n }\n }\n}\n\n/**\n * Produce a new `LoggingData` with every path in `config.paths` replaced\n * by `config.censor`. The original entry is never mutated — channels and\n * other call sites can hold references to the input safely.\n *\n * No-op (returns the input by reference) when `config` is `undefined` or\n * its `paths` array is empty, so the fast path stays fast.\n */\nexport function applyRedact(\n data: LoggingData,\n config: RedactConfig | undefined,\n): LoggingData {\n if (!config || config.paths.length === 0) {\n return data;\n }\n\n const censor = config.censor ?? \"[REDACTED]\";\n const cloned = cloneEntry(data);\n\n for (const pattern of config.paths) {\n const segments = pattern.split(\".\").filter((segment) => segment.length > 0);\n if (segments.length === 0) continue;\n redactAtPath(cloned, segments, censor, []);\n }\n\n return cloned;\n}\n\n/**\n * Combine two redact configs into one effective config. Used to merge a\n * channel's additive paths on top of the logger-wide floor.\n *\n * - `paths` are concatenated; duplicates are kept (the matcher tolerates\n * them, and de-duping cross-config would mask a developer typo).\n * - `censor` from the channel wins; falls back to the logger's; falls back\n * to the default `\"[REDACTED]\"`.\n */\nexport function mergeRedact(\n base: RedactConfig | undefined,\n extra: RedactConfig | undefined,\n): RedactConfig | undefined {\n if (!base && !extra) return undefined;\n if (!base) return extra;\n if (!extra) return base;\n\n return {\n paths: [...base.paths, ...extra.paths],\n censor: extra.censor ?? base.censor,\n };\n}\n"],"mappings":";;;;;;;;;;;AAYA,SAAS,WAAc,OAAU,uBAAO,IAAI,QAAqB,GAAM;CACrE,IAAI,UAAU,QAAQ,OAAO,UAAU,UACrC,OAAO;CAGT,IAAI,KAAK,IAAI,KAA0B,GACrC,OAAO,KAAK,IAAI,KAA0B;CAG5C,IAAI,iBAAiB,MACnB,OAAO,IAAI,KAAK,MAAM,QAAQ,CAAC;CAGjC,IAAI,iBAAiB,OAAO;EAC1B,MAAM,OAAO,IAAK,MAAM,YAAiC,MAAM,OAAO;EACtE,KAAK,QAAQ,MAAM;EACnB,KA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AAQ,IAAI,IAC/C,CAAC,IAAI,IACL,CAAC;CAEX,KAAK,MAAM,OAAO,aAChB,IAAI,KAAK,WAAW,GAClB,OAAO,OAAO,YAAY,OAAO,MAAM,QAAQ,CAAC,GAAG,WAAW,GAAG,CAAC;MAElE,aAAa,OAAO,MAAM,MAAM,QAAQ,CAAC,GAAG,WAAW,GAAG,CAAC;AAGjE;;;;;;;;;AAUA,SAAgB,YACd,MACA,QACa;CACb,IAAI,CAAC,UAAU,OAAO,MAAM,WAAW,GACrC,OAAO;CAGT,MAAM,SAAS,OAAO,UAAU;CAChC,MAAM,SAAS,WAAW,IAAI;CAE9B,KAAK,MAAM,WAAW,OAAO,OAAO;EAClC,MAAM,WAAW,QAAQ,MAAM,GAAG,CAAC,CAAC,QAAQ,YAAY,QAAQ,SAAS,CAAC;EAC1E,IAAI,SAAS,WAAW,GAAG;EAC3B,aAAa,QAAQ,UAAU,QAAQ,CAAC,CAAC;CAC3C;CAEA,OAAO;AACT;;;;;;;;;;AAWA,SAAgB,YACd,MACA,OAC0B;CAC1B,IAAI,CAAC,QAAQ,CAAC,OAAO,OAAO;CAC5B,IAAI,CAAC,MAAM,OAAO;CAClB,IAAI,CAAC,OAAO,OAAO;CAEnB,OAAO;EACL,OAAO,CAAC,GAAG,KAAK,OAAO,GAAG,MAAM,KAAK;EACrC,QAAQ,MAAM,UAAU,KAAK;CAC/B;AACF"}
|
package/esm/types.d.mts
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
|
-
//#region
|
|
2
|
-
|
|
1
|
+
//#region ../@warlock.js/logger/src/types.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Severity levels, ordered debug < info ≈ success < warn < error < fatal.
|
|
4
|
+
*
|
|
5
|
+
* - `debug` — verbose dev diagnostics
|
|
6
|
+
* - `info` / `success` — neutral and explicit-completion events (same severity)
|
|
7
|
+
* - `warn` — recoverable concern
|
|
8
|
+
* - `error` — handled failure; the app continues
|
|
9
|
+
* - `fatal` — unrecoverable failure; the app is going down
|
|
10
|
+
*/
|
|
11
|
+
type LogLevel = "debug" | "info" | "warn" | "error" | "success" | "fatal";
|
|
3
12
|
/**
|
|
4
13
|
* Process-level events that `Logger.enableAutoFlush()` can hook to drain
|
|
5
14
|
* buffered channels before the process terminates.
|
|
@@ -111,13 +120,20 @@ interface LogContract {
|
|
|
111
120
|
* Log the given message
|
|
112
121
|
*/
|
|
113
122
|
log(data: LoggingData): void | Promise<void>;
|
|
123
|
+
/**
|
|
124
|
+
* Asynchronously flush buffered logs. Awaited on a graceful shutdown path
|
|
125
|
+
* (`await log.flush()`); implement this on channels whose delivery is async
|
|
126
|
+
* (network transports, async disk writes) where {@link flushSync} cannot
|
|
127
|
+
* wait on the I/O.
|
|
128
|
+
*/
|
|
129
|
+
flush?(): void | Promise<void>;
|
|
114
130
|
/**
|
|
115
131
|
* Synchronously flush logs
|
|
116
132
|
*/
|
|
117
133
|
flushSync?(): void;
|
|
118
134
|
}
|
|
119
135
|
type LoggingData = {
|
|
120
|
-
type:
|
|
136
|
+
type: LogLevel;
|
|
121
137
|
module: string;
|
|
122
138
|
action: string;
|
|
123
139
|
message: any;
|
package/esm/types.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.mts","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"types.d.mts","names":[],"sources":["../../../../../../@warlock.js/logger/src/types.ts"],"mappings":";;AASA;;;;AAAoB;AAUpB;;;KAVY,QAAA;AAUc;AAQ1B;;;;AAAqB;AAOrB;;AAf0B,KAAd,cAAA;AAAA,KAQA,SAAA;AASkB;AA2B9B;;;;AA3B8B,KAFlB,YAAA,cAEN,KAAA,OAAY,IAAY;;;;AAuCP;AAGvB;;;;;;;;;;;;;;;;;;;;;KAfY,YAAA;EAoCuB;;;;;EA9BjC,KAAA;EAuCU;;;;;EAjCV,MAAA,GAAS,YAAY;AAAA;AAAA,KAGX,sBAAA;EAkCV;;;;;EA5BA,MAAA,GAAS,QAAA;EAgCA;AAAA;AAGX;EA/BE,UAAA;IACE,IAAA;IACA,IAAA;EAAA;EAwDe;;;EAnDjB,MAAA,IAAU,IAAA,EAAM,WAAA;EAiChB;;;EA7BA,OAAA,IAAW,IAAA,EAAM,WAAA,KAAgB,OAAA,CAAQ,MAAA;EAuCrC;;;;;EAjCJ,MAAA,GAAS,YAAA;AAAA;AAAA,KAGC,UAAA;EACV,OAAA;EACA,KAAA,EAAO,QAAA;EACP,IAAA;EACA,MAAA;EACA,MAAA;EACA,KAAA;EACA,OAAA,GAAU,MAAM;EAChB,SAAA;AAAA;AAAA,UAGe,WAAA;EAwCC;AAAA;AAGlB;EAvCE,IAAA;;;AAuC+C;EAlC/C,WAAA;;;;EAKA,QAAA;;;;EAKA,GAAA,CAAI,IAAA,EAAM,WAAA,UAAqB,OAAA;;;;;;;EAQ/B,KAAA,YAAiB,OAAA;;;;EAKjB,SAAA;AAAA;AAAA,KAGU,WAAA;EACV,IAAA,EAAM,QAAA;EACN,MAAA;EACA,MAAA;EACA,OAAA;EACA,OAAA,GAAU,MAAM;AAAA;AAAA,KAGN,kBAAA,GAAqB,IAAI,CAAC,WAAA"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//#region
|
|
1
|
+
//#region ../@warlock.js/logger/src/utils/capture-unhandled-errors.d.ts
|
|
2
2
|
/**
|
|
3
3
|
* Route Node's process-level failure events through the logger so they land in
|
|
4
4
|
* every configured channel with full stack context. Registers one listener for
|
|
@@ -6,6 +6,14 @@
|
|
|
6
6
|
* after channels are configured. Pair with `autoFlushOn: ["beforeExit"]` so the
|
|
7
7
|
* final entry survives the process exit that follows an uncaught exception.
|
|
8
8
|
*
|
|
9
|
+
* Levels chosen for semantic honesty:
|
|
10
|
+
*
|
|
11
|
+
* - `uncaughtException` → `log.fatal` — by default Node terminates the process,
|
|
12
|
+
* so the failure is unrecoverable.
|
|
13
|
+
* - `unhandledRejection` → `log.error` — a rejected promise is a failure, but
|
|
14
|
+
* not necessarily process-ending (depends on Node's `--unhandled-rejections`
|
|
15
|
+
* policy and your app's recovery), so it stays at error.
|
|
16
|
+
*
|
|
9
17
|
* @example
|
|
10
18
|
* log.configure({ channels: [new ConsoleLog(), new FileLog()] });
|
|
11
19
|
* captureAnyUnhandledRejection();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"capture-unhandled-errors.d.mts","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"capture-unhandled-errors.d.mts","names":[],"sources":["../../../../../../../@warlock.js/logger/src/utils/capture-unhandled-errors.ts"],"mappings":";;AAqBA;;;;AAA4C;;;;;;;;;;;;;;iBAA5B,4BAAA"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { log } from "../logger.mjs";
|
|
2
2
|
|
|
3
|
-
//#region
|
|
3
|
+
//#region ../@warlock.js/logger/src/utils/capture-unhandled-errors.ts
|
|
4
4
|
/**
|
|
5
5
|
* Route Node's process-level failure events through the logger so they land in
|
|
6
6
|
* every configured channel with full stack context. Registers one listener for
|
|
@@ -8,6 +8,14 @@ import { log } from "../logger.mjs";
|
|
|
8
8
|
* after channels are configured. Pair with `autoFlushOn: ["beforeExit"]` so the
|
|
9
9
|
* final entry survives the process exit that follows an uncaught exception.
|
|
10
10
|
*
|
|
11
|
+
* Levels chosen for semantic honesty:
|
|
12
|
+
*
|
|
13
|
+
* - `uncaughtException` → `log.fatal` — by default Node terminates the process,
|
|
14
|
+
* so the failure is unrecoverable.
|
|
15
|
+
* - `unhandledRejection` → `log.error` — a rejected promise is a failure, but
|
|
16
|
+
* not necessarily process-ending (depends on Node's `--unhandled-rejections`
|
|
17
|
+
* policy and your app's recovery), so it stays at error.
|
|
18
|
+
*
|
|
11
19
|
* @example
|
|
12
20
|
* log.configure({ channels: [new ConsoleLog(), new FileLog()] });
|
|
13
21
|
* captureAnyUnhandledRejection();
|
|
@@ -17,7 +25,7 @@ function captureAnyUnhandledRejection() {
|
|
|
17
25
|
log.error("app", "unhandledRejection", reason);
|
|
18
26
|
});
|
|
19
27
|
process.on("uncaughtException", (error) => {
|
|
20
|
-
log.
|
|
28
|
+
log.fatal("app", "uncaughtException", error);
|
|
21
29
|
});
|
|
22
30
|
}
|
|
23
31
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"capture-unhandled-errors.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"capture-unhandled-errors.mjs","names":[],"sources":["../../../../../../../@warlock.js/logger/src/utils/capture-unhandled-errors.ts"],"sourcesContent":["import { log } from \"../logger\";\r\n\r\n/**\r\n * Route Node's process-level failure events through the logger so they land in\r\n * every configured channel with full stack context. Registers one listener for\r\n * `unhandledRejection` and one for `uncaughtException`; call once at startup\r\n * after channels are configured. Pair with `autoFlushOn: [\"beforeExit\"]` so the\r\n * final entry survives the process exit that follows an uncaught exception.\r\n *\r\n * Levels chosen for semantic honesty:\r\n *\r\n * - `uncaughtException` → `log.fatal` — by default Node terminates the process,\r\n * so the failure is unrecoverable.\r\n * - `unhandledRejection` → `log.error` — a rejected promise is a failure, but\r\n * not necessarily process-ending (depends on Node's `--unhandled-rejections`\r\n * policy and your app's recovery), so it stays at error.\r\n *\r\n * @example\r\n * log.configure({ channels: [new ConsoleLog(), new FileLog()] });\r\n * captureAnyUnhandledRejection();\r\n */\r\nexport function captureAnyUnhandledRejection() {\r\n process.on(\"unhandledRejection\", (reason: any) => {\r\n log.error(\"app\", \"unhandledRejection\", reason);\r\n });\r\n\r\n process.on(\"uncaughtException\", (error) => {\r\n log.fatal(\"app\", \"uncaughtException\", error);\r\n });\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,+BAA+B;CAC7C,QAAQ,GAAG,uBAAuB,WAAgB;EAChD,IAAI,MAAM,OAAO,sBAAsB,MAAM;CAC/C,CAAC;CAED,QAAQ,GAAG,sBAAsB,UAAU;EACzC,IAAI,MAAM,OAAO,qBAAqB,KAAK;CAC7C,CAAC;AACH"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"clear-message.d.mts","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"clear-message.d.mts","names":[],"sources":["../../../../../../../@warlock.js/logger/src/utils/clear-message.ts"],"mappings":";;AAGA;;iBAAgB,YAAA,CAAa,OAAY"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"clear-message.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"clear-message.mjs","names":[],"sources":["../../../../../../../@warlock.js/logger/src/utils/clear-message.ts"],"sourcesContent":["/**\r\n * Clear message from any terminal codes\r\n */\r\nexport function clearMessage(message: any) {\r\n if (typeof message !== \"string\") return message;\r\n\r\n // eslint-disable-next-line no-control-regex\r\n return message.replace(/\\u001b[^m]*?m/g, \"\");\r\n}\r\n"],"mappings":";;;;AAGA,SAAgB,aAAa,SAAc;CACzC,IAAI,OAAO,YAAY,UAAU,OAAO;CAGxC,OAAO,QAAQ,QAAQ,kBAAkB,EAAE;AAC7C"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//#region
|
|
1
|
+
//#region ../@warlock.js/logger/src/utils/safe-json-stringify.d.ts
|
|
2
2
|
/**
|
|
3
3
|
* JSON-serialize log payloads safely. Circular refs, BigInt, and repeated
|
|
4
4
|
* non-tree references are handled by `safe-stable-stringify`; functions and
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"safe-json-stringify.d.mts","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"safe-json-stringify.d.mts","names":[],"sources":["../../../../../../../@warlock.js/logger/src/utils/safe-json-stringify.ts"],"mappings":";;AAyCA;;;;AAAgE;;;;iBAAhD,iBAAA,CAAkB,KAAA,WAAgB,KAAc"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { stringify } from "safe-stable-stringify";
|
|
2
2
|
|
|
3
|
-
//#region
|
|
3
|
+
//#region ../@warlock.js/logger/src/utils/safe-json-stringify.ts
|
|
4
4
|
/**
|
|
5
5
|
* Replacer that surfaces Error data — `name`, `message`, and `stack` are
|
|
6
6
|
* non-enumerable on `Error`, so neither default JSON serialization nor an
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"safe-json-stringify.mjs","names":["safeStableStringify"],"sources":["
|
|
1
|
+
{"version":3,"file":"safe-json-stringify.mjs","names":["safeStableStringify"],"sources":["../../../../../../../@warlock.js/logger/src/utils/safe-json-stringify.ts"],"sourcesContent":["import { stringify as safeStableStringify } from \"safe-stable-stringify\";\n\n/**\n * Replacer that surfaces Error data — `name`, `message`, and `stack` are\n * non-enumerable on `Error`, so neither default JSON serialization nor an\n * object spread captures them (both produce `{}`). They are copied explicitly;\n * the trailing spread then captures any additional enumerable props the caller\n * (or a subclass) attached, such as a `code` field.\n */\nfunction errorReplacer<Value = unknown>(\n _key: string,\n value: Value,\n): Record<string, unknown> | Value {\n if (value instanceof Error) {\n // Spread first, then the explicit Error fields. `name`/`message`/`stack`\n // are non-enumerable on `Error`, so the spread never carries them — the\n // explicit assignments are what surface them. Placing the spread first\n // means those explicit keys legitimately take precedence over any\n // identically-named *enumerable* prop a subclass attached (resolving the\n // duplicate-key warning). Because `safe-stable-stringify` sorts keys, the\n // insertion order here does not affect the serialized bytes.\n return {\n ...value,\n name: value.name,\n message: value.message,\n stack: value.stack,\n };\n }\n\n return value;\n}\n\n/**\n * JSON-serialize log payloads safely. Circular refs, BigInt, and repeated\n * non-tree references are handled by `safe-stable-stringify`; functions and\n * symbols are dropped (standard JSON behavior); Errors are expanded via\n * `errorReplacer`. Class instances serialize as their enumerable props.\n *\n * @example\n * await fs.promises.writeFile(filePath, safeJsonStringify(payload, 2));\n */\nexport function safeJsonStringify(value: unknown, space?: number): string {\n return safeStableStringify(value, errorReplacer, space) ?? \"\";\n}\n"],"mappings":";;;;;;;;;;AASA,SAAS,cACP,MACA,OACiC;CACjC,IAAI,iBAAiB,OAQnB,OAAO;EACL,GAAG;EACH,MAAM,MAAM;EACZ,SAAS,MAAM;EACf,OAAO,MAAM;CACf;CAGF,OAAO;AACT;;;;;;;;;;AAWA,SAAgB,kBAAkB,OAAgB,OAAwB;CACxE,OAAOA,UAAoB,OAAO,eAAe,KAAK,KAAK;AAC7D"}
|