@warlock.js/logger 5.29.0 → 5.30.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 +25 -0
- package/README.md +6 -6
- package/cjs/index.cjs +233 -29
- 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 +1 -1
- package/esm/channels/console-log.mjs.map +1 -1
- package/esm/channels/file-log.d.mts +1 -1
- package/esm/channels/file-log.d.mts.map +1 -1
- package/esm/channels/file-log.mjs +1 -1
- package/esm/channels/file-log.mjs.map +1 -1
- 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 +1 -1
- package/esm/channels/sentry-log.d.mts.map +1 -1
- package/esm/channels/sentry-log.mjs +1 -1
- package/esm/channels/sentry-log.mjs.map +1 -1
- package/esm/index.d.mts +4 -3
- package/esm/index.mjs +3 -2
- package/esm/log-channel.d.mts +1 -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 +73 -18
- package/esm/logger.d.mts.map +1 -1
- package/esm/logger.mjs +152 -20
- package/esm/logger.mjs.map +1 -1
- package/esm/redact/default-keys.d.mts +1 -1
- package/esm/redact/default-keys.d.mts.map +1 -1
- package/esm/redact/default-keys.mjs +1 -1
- package/esm/redact/default-keys.mjs.map +1 -1
- package/esm/redact/index.mjs +1 -0
- package/esm/redact/mask-email.d.mts +40 -0
- package/esm/redact/mask-email.d.mts.map +1 -0
- package/esm/redact/mask-email.mjs +70 -0
- package/esm/redact/mask-email.mjs.map +1 -0
- 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 +9 -2
- package/esm/types.d.mts.map +1 -1
- package/esm/utils/capture-unhandled-errors.d.mts +1 -1
- package/esm/utils/capture-unhandled-errors.d.mts.map +1 -1
- package/esm/utils/capture-unhandled-errors.mjs +1 -1
- 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 +6 -6
- package/package.json +4 -3
- package/skills/flush-logs-on-shutdown/SKILL.md +2 -2
- package/skills/logger-basics/SKILL.md +3 -3
- package/skills/write-custom-log-channel/SKILL.md +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"console-log.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"console-log.mjs","names":[],"sources":["../../../../../../../../packages/logger/src/channels/console-log.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport { inspect } from \"util\";\nimport { LogChannel } from \"../log-channel\";\nimport type { BasicLogConfigurations, LoggingData, LogLevel } from \"../types\";\n\nexport type ConsoleLogConfig = BasicLogConfigurations & {\n /**\n * Render the log entry's `context` object on a second line after the main\n * message. When `false`, context is silently dropped (the historical\n * behavior). When `true`, contexts are pretty-printed with `util.inspect`\n * — colored, depth-limited, ideal for development. Persistent channels\n * (`FileLog`, `JSONFileLog`) always retain context regardless of this flag.\n *\n * @default false\n */\n showContext?: boolean;\n /**\n * Depth passed to `util.inspect` when rendering context. Only applies when\n * `showContext` is enabled.\n *\n * @default 4\n */\n contextDepth?: number;\n};\n\n/**\n * The longest level name (`success`) sets the tag column width. Padding every\n * level name to this width keeps the timestamp / module / action columns\n * aligned across lines. The level icons are bare (text-style, single-cell)\n * glyphs, so padding the name alone produces true columns.\n */\nconst LEVEL_NAME_WIDTH = 7;\n\n/**\n * Per-level console presentation: the colored, fixed-width `{icon} {name}` tag\n * and the function that colors the message body.\n */\ntype LevelStyle = {\n tag: string;\n message: (message: LoggingData[\"message\"]) => string;\n};\n\n/**\n * Build a single-color, fixed-width tag — `{icon} {name}` with the name padded\n * so every tag spans the same number of columns.\n */\nfunction buildTag(\n icon: string,\n name: string,\n color: (text: string) => string,\n): string {\n return color(`${icon} ${name.padEnd(LEVEL_NAME_WIDTH)}`);\n}\n\n/**\n * Console styling per log level. The `fatal` tag is a bright-red background\n * badge — the same column width as the others (`\" ☠ fatal \"` is 9 cells, like\n * `{icon} {name.padEnd(7)}`), but impossible to miss in a wall of red `error`\n * lines, where a plain red tag would blend in.\n */\nconst LEVEL_STYLES: Record<LogLevel, LevelStyle> = {\n debug: {\n tag: buildTag(\"⚙\", \"debug\", colors.magentaBright),\n message: colors.magentaBright,\n },\n info: {\n tag: buildTag(\"ℹ\", \"info\", colors.blueBright),\n message: colors.blueBright,\n },\n warn: {\n tag: buildTag(\"⚠\", \"warn\", colors.yellow),\n message: colors.yellowBright,\n },\n error: {\n tag: buildTag(\"✗\", \"error\", colors.red),\n message: colors.redBright,\n },\n success: {\n tag: buildTag(\"✓\", \"success\", colors.green),\n message: colors.greenBright,\n },\n fatal: {\n tag: colors.bgRedBright(colors.whiteBright(colors.bold(\" ☠ fatal \"))),\n message: colors.redBright.bold,\n },\n};\n\n/**\n * Fallback for an unrecognized level — a plain `[log]` tag padded to the same\n * width so the columns stay aligned.\n */\nconst DEFAULT_STYLE: LevelStyle = {\n tag: \"[log]\".padEnd(LEVEL_NAME_WIDTH + 2),\n message: message => message as string,\n};\n\nexport class ConsoleLog extends LogChannel<ConsoleLogConfig> {\n /**\n * {@inheritdoc}\n */\n public name = \"console\";\n\n /**\n * Determine if channel is logging in terminal\n */\n public terminal = true;\n\n /**\n * {@inheritdoc}\n */\n public log(data: LoggingData) {\n const { module, action, message, type: level } = data;\n\n if (!this.shouldBeLogged(data)) return;\n\n // Console shows time-only (HH:mm:ss.SSS) — within a dev session the date\n // rarely changes, so the full ISO date + `T`/`Z` are just noise. Persistent\n // channels (FileLog / JSONFileLog) keep the full ISO timestamp.\n const time = new Date().toISOString().slice(11, 23); // i.e. \"10:22:00.000\"\n\n const style = LEVEL_STYLES[level] ?? DEFAULT_STYLE;\n\n // The slate timestamp recedes so the colored level + message lead the eye;\n // module (cyan) and action (magenta) stay colored for subsystem scanning.\n // `slate` (256-color neutral gray) reads cleaner than bright-black `gray`,\n // which sits too close to the background on most terminal themes.\n console.log(\n style.tag,\n colors.slate(`(${time})`),\n colors.cyan(`[${module}]`),\n colors.magenta(`[${action}]`),\n style.message(message),\n );\n\n if (typeof message === \"object\") {\n console.log(message);\n }\n\n // Render context on a second line when explicitly enabled. We only\n // attempt rendering if there's anything meaningful to show — empty\n // objects clutter the terminal without adding signal.\n if (this.config(\"showContext\") && data.context && Object.keys(data.context).length > 0) {\n const depth = this.config(\"contextDepth\") ?? 4;\n console.log(\n colors.slate(\" ↳\"),\n inspect(data.context, { colors: true, depth, breakLength: 80 }),\n );\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AA+BA,MAAM,mBAAmB;;;;;AAezB,SAAS,SACP,MACA,MACA,OACQ;CACR,OAAO,MAAM,GAAG,KAAK,GAAG,KAAK,OAAO,gBAAgB,GAAG;AACzD;;;;;;;AAQA,MAAM,eAA6C;CACjD,OAAO;EACL,KAAK,SAAS,KAAK,SAAS,OAAO,aAAa;EAChD,SAAS,OAAO;CAClB;CACA,MAAM;EACJ,KAAK,SAAS,KAAK,QAAQ,OAAO,UAAU;EAC5C,SAAS,OAAO;CAClB;CACA,MAAM;EACJ,KAAK,SAAS,KAAK,QAAQ,OAAO,MAAM;EACxC,SAAS,OAAO;CAClB;CACA,OAAO;EACL,KAAK,SAAS,KAAK,SA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
|
-
//#region
|
|
4
|
+
//#region ../../packages/logger/src/channels/file-log.d.ts
|
|
5
5
|
type FileLogConfig = BasicLogConfigurations & {
|
|
6
6
|
storagePath?: string;
|
|
7
7
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-log.d.mts","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"file-log.d.mts","names":[],"sources":["../../../../../../../../packages/logger/src/channels/file-log.ts"],"mappings":";;;;KAgBY,aAAA,GAAgB,sBAAA;EAC1B,WAAA;EADU;;;EAKV,IAAA;EAL0B;;;;;;;EAa1B,KAAA;EA8BA;;;;;EAxBA,MAAA;EA4CE;;AAAI;AAIR;;EA1CE,SAAA;EA0CsC;;;;;EApCtC,cAAA;EA6F2D;;;;;EAvF3D,WAAA;EA2T8C;;;;;EArT9C,kBAAA;EAwB2E;;;;;;;EAhB3E,OAAA;EA8BU;;;;;EAxBV,MAAA,GAAS,QAAQ;EAuDP;;;EAnDV,UAAA;IACE,IAAA;IACA,IAAA;EAAA;AAAA;AAAA,cAIS,OAAA,SAAgB,UAAA,CAAW,aAAA,aAA0B,WAAA;EAiGtD;;;EA7FH,IAAA;EA6II;;;EAAA,UAxID,QAAA,EAAU,UAAA;EA8KJ;;;EAAA,UAzKN,eAAA,EAAiB,MAAA,SAAe,UAAA;EAqNpB;;;EAAA,UAhNZ,qBAAA,EAAuB,aAAA;EAiOC;;;EAAA,UA5MxB,aAAA;EAwQI;;;EAAA,UAnQJ,SAAA;EAkSoC;;;;;EAAA,UA3RpC,mBAAA,GAAsB,MAAA,CAAO,OAAA;EAuUgB;AAAA;;EAAA,UAlUvC,kBAAA,CAAmB,QAAA,YAAwB,OAAA;;;;YAoB3C,aAAA,IAAa,OAAA;;;;;;;;;YAoBnB,gBAAA;;;;;;;;EAkBH,OAAA;;;;MAYI,QAAA;;;;gBAWG,kBAAA;;;;MAOH,QAAA;;;;MAiBA,SAAA;;;;gBAOG,OAAA;;;;MAOH,WAAA;;;;YAOK,IAAA,IAAI,OAAA;;;;EAWb,SAAA;;;;;;;;;;EAiCM,KAAA,IAAS,OAAA;;;;EAiBT,GAAA,CAAI,IAAA,EAAM,WAAA,GAAW,OAAA;;;;YAyClB,8BAAA,IAA8B,OAAA;;;;YASpC,MAAA;;;;gBAUI,uBAAA;;;;YAOE,mBAAA,IAAmB,OAAA;;;;YAwBnB,0BAAA,IAA8B,OAAA;;;;YA8BpC,sBAAA;;;;YAcM,KAAA,CAAM,QAAA,UAAkB,OAAA,WAAe,OAAA;AAAA"}
|
|
@@ -5,7 +5,7 @@ import fs from "fs";
|
|
|
5
5
|
import { EOL } from "os";
|
|
6
6
|
import path from "path";
|
|
7
7
|
|
|
8
|
-
//#region
|
|
8
|
+
//#region ../../packages/logger/src/channels/file-log.ts
|
|
9
9
|
var FileLog = class extends LogChannel {
|
|
10
10
|
constructor(..._args) {
|
|
11
11
|
super(..._args);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-log.mjs","names":[],"sources":["../../../../../../../logger/src/channels/file-log.ts"],"sourcesContent":["import { ensureDirectoryAsync } from \"@warlock.js/fs\";\nimport dayjs from \"dayjs\";\nimport fs from \"fs\";\nimport { EOL } from \"os\";\nimport path from \"path\";\nimport { LogChannel } from \"../log-channel\";\nimport type {\n BasicLogConfigurations,\n LogContract,\n LoggingData,\n LogLevel,\n LogMessage,\n} from \"../types\";\n\n// TODO: Add max messages per file before rotation\n\nexport type FileLogConfig = BasicLogConfigurations & {\n storagePath?: string;\n /**\n * File name, without extension\n */\n name?: string;\n /**\n * chunk mode\n * If set to `single`, the logs will be created in a single file, unless the rotate is set to true\n * If set to `daily`, the logs will be created in a daily file, unless the rotate is set to true\n * If set to `hourly`, the logs will be created in an hourly file, unless the rotate is set to true\n * @default single\n */\n chunk?: \"single\" | \"daily\" | \"hourly\";\n /**\n * Whether to rotate the file\n *\n * @default true\n */\n rotate?: boolean;\n /**\n * File Extension\n *\n * @default log\n */\n extension?: string;\n /**\n * If rotate is set, the rotate name will be added to the file name suffixed with `-`\n *\n * @default DD-MM-YYYY\n */\n rotateFileName?: string;\n /**\n * Max file size before rotating the file\n *\n * @default 10MB\n */\n maxFileSize?: number;\n /**\n * Set the max messages that needs to be added before writing to the file\n *\n * @default 100\n */\n maxMessagesToWrite?: number;\n /**\n * Group logs by\n * Please note that the order matters here\n * For example, if you set `groupBy: ['level', 'module']`, the logs will be added in level name first, then by module\n *\n * @default none\n */\n groupBy?: (\"level\" | \"module\" | \"action\")[];\n /**\n * Define what levels should be logged\n *\n * @default all\n */\n levels?: LogLevel[];\n /**\n * Date and time format\n */\n dateFormat?: {\n date?: string;\n time?: string;\n };\n};\n\nexport class FileLog extends LogChannel<FileLogConfig> implements LogContract {\n /**\n * {@inheritdoc}\n */\n public name = \"file\";\n\n /**\n * Messages buffer\n */\n protected messages: LogMessage[] = [];\n\n /**\n * Grouped messages\n */\n protected groupedMessages: Record<string, LogMessage[]> = {};\n\n /**\n * Default channel configurations\n */\n protected defaultConfigurations: FileLogConfig = {\n storagePath: process.cwd() + \"/storage/logs\",\n rotate: true,\n name: \"app\",\n extension: \"log\",\n chunk: \"single\",\n maxMessagesToWrite: 100,\n filter: () => true,\n maxFileSize: 10 * 1024 * 1024, // 10MB\n get rotateFileName() {\n return dayjs().format(\"DD-MM-YYYY\");\n },\n dateFormat: {\n date: \"DD-MM-YYYY\",\n time: \"HH:mm:ss\",\n },\n };\n\n /**\n * Last write time\n */\n protected lastWriteTime = Date.now();\n\n /**\n * A flag to determine if the file is being written\n */\n protected isWriting = false;\n\n /**\n * Handle for the periodic flush interval. Stored so it can be cleared\n * in `dispose()` — long-lived processes that create channels dynamically\n * would otherwise leak one timer per channel.\n */\n protected flushIntervalHandle?: NodeJS.Timeout;\n\n /**\n * Check file size for file rotation\n */\n protected async checkAndRotateFile(filePath = this.filePath) {\n if (!this.config(\"rotate\")) return;\n\n try {\n const stats = await fs.promises.stat(filePath);\n if (stats.size >= this.config(\"maxFileSize\")!) {\n await this.rotateLogFile();\n }\n } catch (error: any) {\n // ENOENT is expected when the file hasn't been created yet — there is\n // nothing to rotate, so stay silent. Surface anything else.\n if (error.code !== \"ENOENT\") {\n console.error(\"Error checking log file:\", error);\n }\n }\n }\n\n /**\n * Rotate log file\n */\n protected async rotateLogFile() {\n const fileName = `${this.fileName}-${this.config(\"rotateFileName\")}-${Date.now()}`;\n\n const extension = this.extension;\n\n const rotatedFilePath = path.join(this.storagePath, `${fileName}.${extension}`);\n\n await fs.promises.rename(this.filePath, rotatedFilePath).catch((error) => {\n console.error(\"Error rotating file:\", error);\n });\n }\n\n /**\n * Flush messages\n *\n * Starts a periodic re-check so low-traffic channels don't sit on buffered\n * entries indefinitely. The handle is stored on the instance so `dispose()`\n * can stop it — without this, every channel leaks a timer for the lifetime\n * of the process.\n */\n protected initMessageFlush() {\n this.flushIntervalHandle = setInterval(() => {\n if (\n this.messages.length > 0 &&\n (this.messages.length >= this.maxMessagesToWrite || Date.now() - this.lastWriteTime > 5000)\n ) {\n this.writeMessagesToFile();\n }\n }, 5000);\n }\n\n /**\n * Stop the background flush interval and drain any buffered entries.\n *\n * Call this when discarding a channel (e.g. reconfiguring the logger at\n * runtime) so the 5-second timer doesn't keep the event loop alive. Safe to\n * call more than once.\n */\n public dispose(): void {\n if (this.flushIntervalHandle) {\n clearInterval(this.flushIntervalHandle);\n this.flushIntervalHandle = undefined;\n }\n\n this.flushSync();\n }\n\n /**\n * Get file path\n */\n public get filePath() {\n const fileName = this.fileName;\n\n const extension = this.extension;\n\n return path.join(this.storagePath, `${fileName}.${extension}`);\n }\n\n /**\n * Get max messages\n */\n protected get maxMessagesToWrite(): number {\n return this.config(\"maxMessagesToWrite\")!;\n }\n\n /**\n * Get file name\n */\n public get fileName(): string {\n const debugLevel = this.config(\"chunk\")!;\n\n switch (debugLevel) {\n case \"single\":\n default:\n return this.config(\"name\")!;\n case \"daily\":\n return dayjs().format(\"DD-MM-YYYY\");\n case \"hourly\":\n return dayjs().format(\"DD-MM-YYYY-HH-00-00-a\");\n }\n }\n\n /**\n * Get file extension\n */\n public get extension(): string {\n return this.config(\"extension\")!;\n }\n\n /**\n * Get content\n */\n protected get content() {\n return this.messages.map((message) => message.content).join(EOL) + EOL;\n }\n\n /**\n * Get storage path\n */\n public get storagePath(): string {\n return this.config(\"storagePath\")!;\n }\n\n /**\n * {@inheritdoc}\n */\n protected async init() {\n const logsDirectory = this.storagePath;\n\n await ensureDirectoryAsync(logsDirectory);\n\n this.initMessageFlush();\n }\n\n /**\n * Synchronously flush messages\n */\n public flushSync(): void {\n if (this.messages.length === 0 && Object.keys(this.groupedMessages).length === 0) return;\n\n if (this.messagedShouldBeGrouped) {\n this.prepareGroupedMessages();\n // `Object.entries` rather than `for...in` + index: under\n // `noUncheckedIndexedAccess` an index read is `LogMessage[] | undefined`\n // even when the key came from the object itself, and entries hands over\n // the value already narrowed. Same iteration, no assertion.\n for (const [key, groupMessages] of Object.entries(this.groupedMessages)) {\n const directoryPath = path.join(this.storagePath, key);\n fs.mkdirSync(directoryPath, { recursive: true });\n const filePath = path.join(directoryPath, `${this.fileName}.${this.extension}`);\n const content = groupMessages.map((message) => message.content).join(EOL) + EOL;\n fs.appendFileSync(filePath, content);\n }\n } else {\n fs.mkdirSync(this.storagePath, { recursive: true });\n fs.appendFileSync(this.filePath, this.content);\n }\n\n this.onSave();\n }\n\n /**\n * Asynchronously drain buffered entries to disk.\n *\n * The async analogue of {@link flushSync}: it reuses the same async writer\n * as the background interval, so a caller on a graceful-shutdown path can\n * `await channel.flush()` (or `await log.flush()`) and rely on the buffer\n * being on disk once it resolves. `JSONFileLog` inherits this unchanged —\n * its overridden `writeMessagesToFile` performs the JSON merge.\n */\n public async flush(): Promise<void> {\n if (this.messages.length === 0 && Object.keys(this.groupedMessages).length === 0) {\n return;\n }\n\n // Clear the in-flight lock so a deliberate drain is never short-circuited\n // by a half-finished background write, then await the async writer to\n // completion — unlike the fire-and-forget interval, callers depend on the\n // buffer reaching disk before this resolves.\n this.isWriting = false;\n\n await this.writeMessagesToFile();\n }\n\n /**\n * {@inheritdoc}\n */\n public async log(data: LoggingData) {\n const { module, action, message, type: level, context } = data;\n\n if (!this.shouldBeLogged(data)) return;\n\n const { date: dateFormat, time } = this.getDateAndTimeFormat();\n\n const date = dayjs().format(dateFormat + \" \" + time);\n\n let content = `[${date}] [${level}] [${module}][${action}]: `;\n\n let stack: string | undefined;\n\n // check if message is an instance of Error\n if (message instanceof Error) {\n // in that case we need to store the error message and stack trace\n content += message.message + EOL;\n content += `[trace]` + EOL;\n content += message.stack;\n stack = message.stack;\n } else {\n content += message;\n }\n\n this.messages.push({\n content,\n level,\n date,\n module,\n action,\n stack,\n context,\n timestamp: new Date().toISOString(),\n });\n\n await this.checkIfMessagesShouldBeWritten(); // Immediate check on buffer size\n }\n\n /**\n * Check if messages should be written\n */\n protected async checkIfMessagesShouldBeWritten() {\n if (this.messages.length >= this.maxMessagesToWrite || Date.now() - this.lastWriteTime > 5000) {\n await this.writeMessagesToFile();\n }\n }\n\n /**\n * Should be called after messages are saved\n */\n protected onSave() {\n this.messages = [];\n this.groupedMessages = {};\n this.isWriting = false;\n this.lastWriteTime = Date.now();\n }\n\n /**\n * Check if messages should be grouped\n */\n protected get messagedShouldBeGrouped(): boolean {\n return Number(this.config(\"groupBy\")?.length) > 0;\n }\n\n /**\n * Write messages to the file\n */\n protected async writeMessagesToFile() {\n if (this.messages.length === 0 || this.isWriting || !this.isInitialized) return;\n\n this.isWriting = true;\n\n if (this.messagedShouldBeGrouped) {\n return await this.writeGroupedMessagesToFile();\n }\n\n await this.checkAndRotateFile(); // Ensure we check file size before writing\n\n try {\n await this.write(this.filePath, this.content);\n this.onSave();\n } catch (error) {\n console.error(\"Failed to write log:\", error);\n // Implement fallback logic here\n this.isWriting = false;\n }\n }\n\n /**\n * Write grouped messages to the file\n */\n protected async writeGroupedMessagesToFile(): Promise<void> {\n // first step, is to group the messages\n this.prepareGroupedMessages();\n\n // now each key in the grouped messages, represents the directory path that should extend the storage path\n for (const [key, groupMessages] of Object.entries(this.groupedMessages)) {\n const directoryPath = path.join(this.storagePath, key);\n\n await ensureDirectoryAsync(directoryPath);\n\n const filePath = path.join(directoryPath, `${this.fileName}.${this.extension}`);\n\n await this.checkAndRotateFile(filePath); // Ensure we check file size before writing\n\n const content = groupMessages.map((message) => message.content).join(EOL) + EOL;\n\n try {\n await this.write(filePath, content);\n } catch (error) {\n console.error(\"Failed to write log:\", error);\n }\n }\n\n this.onSave();\n this.isWriting = false;\n }\n\n /**\n * Prepare grouped messages\n */\n protected prepareGroupedMessages(): void {\n this.messages.forEach((message) => {\n const key = this.config(\"groupBy\")!\n .map((groupKey) => encodeURIComponent(message[groupKey]))\n .join(\"/\");\n\n this.groupedMessages[key] = this.groupedMessages[key] || [];\n this.groupedMessages[key].push(message);\n });\n }\n\n /**\n * Start writing to the file\n */\n protected async write(filePath: string, content: string) {\n return new Promise((resolve, reject) => {\n const writer = fs.createWriteStream(filePath, { flags: \"a\" });\n\n writer.write(content, (error) => {\n writer.end();\n if (error) {\n reject(error);\n } else {\n resolve(true);\n }\n });\n });\n }\n}\n"],"mappings":";;;;;;;;AAmFA,IAAa,UAAb,cAA6B,WAAiD;;;cAI9D;kBAKqB,CAAC;yBAKsB,CAAC;+BAKV;GAC/C,aAAa,QAAQ,IAAI,IAAI;GAC7B,QAAQ;GACR,MAAM;GACN,WAAW;GACX,OAAO;GACP,oBAAoB;GACpB,cAAc;GACd,aAAa,KAAK,OAAO;GACzB,IAAI,iBAAiB;IACnB,OAAO,MAAM,CAAC,CAAC,OAAO,YAAY;GACpC;GACA,YAAY;IACV,MAAM;IACN,MAAM;GACR;EACF;uBAK0B,KAAK,IAAI;mBAKb;;;;;CAYtB,MAAgB,mBAAmB,WAAW,KAAK,UAAU;EAC3D,IAAI,CAAC,KAAK,OAAO,QAAQ,GAAG;EAE5B,IAAI;GAEF,KAAI,MADgB,GAAG,SAAS,KAAK,QAAQ,EACpC,CAAC,QAAQ,KAAK,OAAO,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A4C;EAE1D,KAAK,uBAAuB;EAG5B,KAAK,MAAM,CAAC,KAAK,kBAAkB,OAAO,QAAQ,KAAK,eAAe,GAAG;GACvE,MAAM,gBAAgB,KAAK,KAAK,KAAK,aAAa,GAAG;GAErD,MAAM,qBAAqB,aAAa;GAExC,MAAM,WAAW,KAAK,KAAK,eAAe,GAAG,KAAK,SAAS,GAAG,KAAK,WAAW;GAE9E,MAAM,KAAK,mBAAmB,QAAQ;GAEtC,MAAM,UAAU,cAAc,KAAK,YAAY,QAAQ,OAAO,CAAC,CAAC,KAAK,GAAG,IAAI;GAE5E,IAAI;IACF,MAAM,KAAK,MAAM,UAAU,OAAO;GACpC,SAAS,OAAO;IACd,QAAQ,MAAM,wBAAwB,KAAK;GAC7C;EACF;EAEA,KAAK,OAAO;EACZ,KAAK,YAAY;CACnB;;;;CAKA,AAAU,yBAA+B;EACvC,KAAK,SAAS,SAAS,YAAY;GACjC,MAAM,MAAM,KAAK,OAAO,SAAS,CAAC,CAC/B,KAAK,aAAa,mBAAmB,QAAQ,SAAS,CAAC,CAAC,CACxD,KAAK,GAAG;GAEX,KAAK,gBAAgB,OAAO,KAAK,gBAAgB,QAAQ,CAAC;GAC1D,KAAK,gBAAgB,IAAI,CAAC,KAAK,OAAO;EACxC,CAAC;CACH;;;;CAKA,MAAgB,MAAM,UAAkB,SAAiB;EACvD,OAAO,IAAI,SAAS,SAAS,WAAW;GACtC,MAAM,SAAS,GAAG,kBAAkB,UAAU,EAAE,OAAO,IAAI,CAAC;GAE5D,OAAO,MAAM,UAAU,UAAU;IAC/B,OAAO,IAAI;IACX,IAAI,OACF,OAAO,KAAK;SAEZ,QAAQ,IAAI;GAEhB,CAAC;EACH,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"file-log.mjs","names":[],"sources":["../../../../../../../../packages/logger/src/channels/file-log.ts"],"sourcesContent":["import { ensureDirectoryAsync } from \"@warlock.js/fs\";\nimport dayjs from \"dayjs\";\nimport fs from \"fs\";\nimport { EOL } from \"os\";\nimport path from \"path\";\nimport { LogChannel } from \"../log-channel\";\nimport type {\n BasicLogConfigurations,\n LogContract,\n LoggingData,\n LogLevel,\n LogMessage,\n} from \"../types\";\n\n// TODO: Add max messages per file before rotation\n\nexport type FileLogConfig = BasicLogConfigurations & {\n storagePath?: string;\n /**\n * File name, without extension\n */\n name?: string;\n /**\n * chunk mode\n * If set to `single`, the logs will be created in a single file, unless the rotate is set to true\n * If set to `daily`, the logs will be created in a daily file, unless the rotate is set to true\n * If set to `hourly`, the logs will be created in an hourly file, unless the rotate is set to true\n * @default single\n */\n chunk?: \"single\" | \"daily\" | \"hourly\";\n /**\n * Whether to rotate the file\n *\n * @default true\n */\n rotate?: boolean;\n /**\n * File Extension\n *\n * @default log\n */\n extension?: string;\n /**\n * If rotate is set, the rotate name will be added to the file name suffixed with `-`\n *\n * @default DD-MM-YYYY\n */\n rotateFileName?: string;\n /**\n * Max file size before rotating the file\n *\n * @default 10MB\n */\n maxFileSize?: number;\n /**\n * Set the max messages that needs to be added before writing to the file\n *\n * @default 100\n */\n maxMessagesToWrite?: number;\n /**\n * Group logs by\n * Please note that the order matters here\n * For example, if you set `groupBy: ['level', 'module']`, the logs will be added in level name first, then by module\n *\n * @default none\n */\n groupBy?: (\"level\" | \"module\" | \"action\")[];\n /**\n * Define what levels should be logged\n *\n * @default all\n */\n levels?: LogLevel[];\n /**\n * Date and time format\n */\n dateFormat?: {\n date?: string;\n time?: string;\n };\n};\n\nexport class FileLog extends LogChannel<FileLogConfig> implements LogContract {\n /**\n * {@inheritdoc}\n */\n public name = \"file\";\n\n /**\n * Messages buffer\n */\n protected messages: LogMessage[] = [];\n\n /**\n * Grouped messages\n */\n protected groupedMessages: Record<string, LogMessage[]> = {};\n\n /**\n * Default channel configurations\n */\n protected defaultConfigurations: FileLogConfig = {\n storagePath: process.cwd() + \"/storage/logs\",\n rotate: true,\n name: \"app\",\n extension: \"log\",\n chunk: \"single\",\n maxMessagesToWrite: 100,\n filter: () => true,\n maxFileSize: 10 * 1024 * 1024, // 10MB\n get rotateFileName() {\n return dayjs().format(\"DD-MM-YYYY\");\n },\n dateFormat: {\n date: \"DD-MM-YYYY\",\n time: \"HH:mm:ss\",\n },\n };\n\n /**\n * Last write time\n */\n protected lastWriteTime = Date.now();\n\n /**\n * A flag to determine if the file is being written\n */\n protected isWriting = false;\n\n /**\n * Handle for the periodic flush interval. Stored so it can be cleared\n * in `dispose()` — long-lived processes that create channels dynamically\n * would otherwise leak one timer per channel.\n */\n protected flushIntervalHandle?: NodeJS.Timeout;\n\n /**\n * Check file size for file rotation\n */\n protected async checkAndRotateFile(filePath = this.filePath) {\n if (!this.config(\"rotate\")) return;\n\n try {\n const stats = await fs.promises.stat(filePath);\n if (stats.size >= this.config(\"maxFileSize\")!) {\n await this.rotateLogFile();\n }\n } catch (error: any) {\n // ENOENT is expected when the file hasn't been created yet — there is\n // nothing to rotate, so stay silent. Surface anything else.\n if (error.code !== \"ENOENT\") {\n console.error(\"Error checking log file:\", error);\n }\n }\n }\n\n /**\n * Rotate log file\n */\n protected async rotateLogFile() {\n const fileName = `${this.fileName}-${this.config(\"rotateFileName\")}-${Date.now()}`;\n\n const extension = this.extension;\n\n const rotatedFilePath = path.join(this.storagePath, `${fileName}.${extension}`);\n\n await fs.promises.rename(this.filePath, rotatedFilePath).catch((error) => {\n console.error(\"Error rotating file:\", error);\n });\n }\n\n /**\n * Flush messages\n *\n * Starts a periodic re-check so low-traffic channels don't sit on buffered\n * entries indefinitely. The handle is stored on the instance so `dispose()`\n * can stop it — without this, every channel leaks a timer for the lifetime\n * of the process.\n */\n protected initMessageFlush() {\n this.flushIntervalHandle = setInterval(() => {\n if (\n this.messages.length > 0 &&\n (this.messages.length >= this.maxMessagesToWrite || Date.now() - this.lastWriteTime > 5000)\n ) {\n this.writeMessagesToFile();\n }\n }, 5000);\n }\n\n /**\n * Stop the background flush interval and drain any buffered entries.\n *\n * Call this when discarding a channel (e.g. reconfiguring the logger at\n * runtime) so the 5-second timer doesn't keep the event loop alive. Safe to\n * call more than once.\n */\n public dispose(): void {\n if (this.flushIntervalHandle) {\n clearInterval(this.flushIntervalHandle);\n this.flushIntervalHandle = undefined;\n }\n\n this.flushSync();\n }\n\n /**\n * Get file path\n */\n public get filePath() {\n const fileName = this.fileName;\n\n const extension = this.extension;\n\n return path.join(this.storagePath, `${fileName}.${extension}`);\n }\n\n /**\n * Get max messages\n */\n protected get maxMessagesToWrite(): number {\n return this.config(\"maxMessagesToWrite\")!;\n }\n\n /**\n * Get file name\n */\n public get fileName(): string {\n const debugLevel = this.config(\"chunk\")!;\n\n switch (debugLevel) {\n case \"single\":\n default:\n return this.config(\"name\")!;\n case \"daily\":\n return dayjs().format(\"DD-MM-YYYY\");\n case \"hourly\":\n return dayjs().format(\"DD-MM-YYYY-HH-00-00-a\");\n }\n }\n\n /**\n * Get file extension\n */\n public get extension(): string {\n return this.config(\"extension\")!;\n }\n\n /**\n * Get content\n */\n protected get content() {\n return this.messages.map((message) => message.content).join(EOL) + EOL;\n }\n\n /**\n * Get storage path\n */\n public get storagePath(): string {\n return this.config(\"storagePath\")!;\n }\n\n /**\n * {@inheritdoc}\n */\n protected async init() {\n const logsDirectory = this.storagePath;\n\n await ensureDirectoryAsync(logsDirectory);\n\n this.initMessageFlush();\n }\n\n /**\n * Synchronously flush messages\n */\n public flushSync(): void {\n if (this.messages.length === 0 && Object.keys(this.groupedMessages).length === 0) return;\n\n if (this.messagedShouldBeGrouped) {\n this.prepareGroupedMessages();\n // `Object.entries` rather than `for...in` + index: under\n // `noUncheckedIndexedAccess` an index read is `LogMessage[] | undefined`\n // even when the key came from the object itself, and entries hands over\n // the value already narrowed. Same iteration, no assertion.\n for (const [key, groupMessages] of Object.entries(this.groupedMessages)) {\n const directoryPath = path.join(this.storagePath, key);\n fs.mkdirSync(directoryPath, { recursive: true });\n const filePath = path.join(directoryPath, `${this.fileName}.${this.extension}`);\n const content = groupMessages.map((message) => message.content).join(EOL) + EOL;\n fs.appendFileSync(filePath, content);\n }\n } else {\n fs.mkdirSync(this.storagePath, { recursive: true });\n fs.appendFileSync(this.filePath, this.content);\n }\n\n this.onSave();\n }\n\n /**\n * Asynchronously drain buffered entries to disk.\n *\n * The async analogue of {@link flushSync}: it reuses the same async writer\n * as the background interval, so a caller on a graceful-shutdown path can\n * `await channel.flush()` (or `await log.flush()`) and rely on the buffer\n * being on disk once it resolves. `JSONFileLog` inherits this unchanged —\n * its overridden `writeMessagesToFile` performs the JSON merge.\n */\n public async flush(): Promise<void> {\n if (this.messages.length === 0 && Object.keys(this.groupedMessages).length === 0) {\n return;\n }\n\n // Clear the in-flight lock so a deliberate drain is never short-circuited\n // by a half-finished background write, then await the async writer to\n // completion — unlike the fire-and-forget interval, callers depend on the\n // buffer reaching disk before this resolves.\n this.isWriting = false;\n\n await this.writeMessagesToFile();\n }\n\n /**\n * {@inheritdoc}\n */\n public async log(data: LoggingData) {\n const { module, action, message, type: level, context } = data;\n\n if (!this.shouldBeLogged(data)) return;\n\n const { date: dateFormat, time } = this.getDateAndTimeFormat();\n\n const date = dayjs().format(dateFormat + \" \" + time);\n\n let content = `[${date}] [${level}] [${module}][${action}]: `;\n\n let stack: string | undefined;\n\n // check if message is an instance of Error\n if (message instanceof Error) {\n // in that case we need to store the error message and stack trace\n content += message.message + EOL;\n content += `[trace]` + EOL;\n content += message.stack;\n stack = message.stack;\n } else {\n content += message;\n }\n\n this.messages.push({\n content,\n level,\n date,\n module,\n action,\n stack,\n context,\n timestamp: new Date().toISOString(),\n });\n\n await this.checkIfMessagesShouldBeWritten(); // Immediate check on buffer size\n }\n\n /**\n * Check if messages should be written\n */\n protected async checkIfMessagesShouldBeWritten() {\n if (this.messages.length >= this.maxMessagesToWrite || Date.now() - this.lastWriteTime > 5000) {\n await this.writeMessagesToFile();\n }\n }\n\n /**\n * Should be called after messages are saved\n */\n protected onSave() {\n this.messages = [];\n this.groupedMessages = {};\n this.isWriting = false;\n this.lastWriteTime = Date.now();\n }\n\n /**\n * Check if messages should be grouped\n */\n protected get messagedShouldBeGrouped(): boolean {\n return Number(this.config(\"groupBy\")?.length) > 0;\n }\n\n /**\n * Write messages to the file\n */\n protected async writeMessagesToFile() {\n if (this.messages.length === 0 || this.isWriting || !this.isInitialized) return;\n\n this.isWriting = true;\n\n if (this.messagedShouldBeGrouped) {\n return await this.writeGroupedMessagesToFile();\n }\n\n await this.checkAndRotateFile(); // Ensure we check file size before writing\n\n try {\n await this.write(this.filePath, this.content);\n this.onSave();\n } catch (error) {\n console.error(\"Failed to write log:\", error);\n // Implement fallback logic here\n this.isWriting = false;\n }\n }\n\n /**\n * Write grouped messages to the file\n */\n protected async writeGroupedMessagesToFile(): Promise<void> {\n // first step, is to group the messages\n this.prepareGroupedMessages();\n\n // now each key in the grouped messages, represents the directory path that should extend the storage path\n for (const [key, groupMessages] of Object.entries(this.groupedMessages)) {\n const directoryPath = path.join(this.storagePath, key);\n\n await ensureDirectoryAsync(directoryPath);\n\n const filePath = path.join(directoryPath, `${this.fileName}.${this.extension}`);\n\n await this.checkAndRotateFile(filePath); // Ensure we check file size before writing\n\n const content = groupMessages.map((message) => message.content).join(EOL) + EOL;\n\n try {\n await this.write(filePath, content);\n } catch (error) {\n console.error(\"Failed to write log:\", error);\n }\n }\n\n this.onSave();\n this.isWriting = false;\n }\n\n /**\n * Prepare grouped messages\n */\n protected prepareGroupedMessages(): void {\n this.messages.forEach((message) => {\n const key = this.config(\"groupBy\")!\n .map((groupKey) => encodeURIComponent(message[groupKey]))\n .join(\"/\");\n\n this.groupedMessages[key] = this.groupedMessages[key] || [];\n this.groupedMessages[key].push(message);\n });\n }\n\n /**\n * Start writing to the file\n */\n protected async write(filePath: string, content: string) {\n return new Promise((resolve, reject) => {\n const writer = fs.createWriteStream(filePath, { flags: \"a\" });\n\n writer.write(content, (error) => {\n writer.end();\n if (error) {\n reject(error);\n } else {\n resolve(true);\n }\n });\n });\n }\n}\n"],"mappings":";;;;;;;;AAmFA,IAAa,UAAb,cAA6B,WAAi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1D,KAAK,gBAAgB,IAAI,CAAC,KAAK,OAAO;EACxC,CAAC;CACH;;;;CAKA,MAAgB,MAAM,UAAkB,SAAiB;EACvD,OAAO,IAAI,SAAS,SAAS,WAAW;GACtC,MAAM,SAAS,GAAG,kBAAkB,UAAU,EAAE,OAAO,IAAI,CAAC;GAE5D,OAAO,MAAM,UAAU,UAAU;IAC/B,OAAO,IAAI;IACX,IAAI,OACF,OAAO,KAAK;SAEZ,QAAQ,IAAI;GAEhB,CAAC;EACH,CAAC;CACH;AACF"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { LogContract, LoggingData } from "../types.mjs";
|
|
2
2
|
import { FileLog } from "./file-log.mjs";
|
|
3
3
|
|
|
4
|
-
//#region
|
|
4
|
+
//#region ../../packages/logger/src/channels/json-file-log.d.ts
|
|
5
5
|
declare class JSONFileLog extends FileLog implements LogContract {
|
|
6
6
|
/**
|
|
7
7
|
* {@inheritdoc}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json-file-log.d.mts","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"json-file-log.d.mts","names":[],"sources":["../../../../../../../../packages/logger/src/channels/json-file-log.ts"],"mappings":";;;;cAQa,WAAA,SAAoB,OAAA,YAAmB,WAAA;;AAApD;;EAIS,IAAA;EA4DgB;;;EAAA,IAvDZ,SAAA;EAToB;;;EAgBxB,SAAA;EAhBwB;;;EAgElB,GAAA,CAAI,IAAA,EAAM,WAAA,GAAW,OAAA;EAhD3B;;;EAAA,UAiFS,mBAAA,IAAuB,OAAA;EAjCL;;;EAAA,UAyElB,0BAAA,IAA8B,OAAA;AAAA"}
|
|
@@ -5,7 +5,7 @@ import dayjs from "dayjs";
|
|
|
5
5
|
import fs from "fs";
|
|
6
6
|
import path from "path";
|
|
7
7
|
|
|
8
|
-
//#region
|
|
8
|
+
//#region ../../packages/logger/src/channels/json-file-log.ts
|
|
9
9
|
var JSONFileLog = class extends FileLog {
|
|
10
10
|
constructor(..._args) {
|
|
11
11
|
super(..._args);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json-file-log.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"json-file-log.mjs","names":[],"sources":["../../../../../../../../packages/logger/src/channels/json-file-log.ts"],"sourcesContent":["import { ensureDirectoryAsync, fileExistsAsync, getJsonFileAsync } from \"@warlock.js/fs\";\nimport dayjs from \"dayjs\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport type { LogContract, LogMessage, LoggingData } from \"../types\";\nimport { safeJsonStringify } from \"../utils/safe-json-stringify\";\nimport { FileLog } from \"./file-log\";\n\nexport class JSONFileLog extends FileLog implements LogContract {\n /**\n * {@inheritdoc}\n */\n public name = \"fileJson\";\n\n /**\n * Get file extension\n */\n public get extension(): string {\n return \"json\";\n }\n\n /**\n * Synchronously flush messages\n */\n public flushSync(): void {\n if (this.messages.length === 0 && Object.keys(this.groupedMessages).length === 0) return;\n\n if (this.messagedShouldBeGrouped) {\n this.prepareGroupedMessages();\n // `Object.entries` rather than `for...in` + index: under\n // `noUncheckedIndexedAccess` the index read is `LogMessage[] |\n // undefined`, and spreading that into `push` is a type error rather than\n // a runtime one only because the key demonstrably exists. Entries says so\n // to the compiler instead of asserting it.\n for (const [key, groupMessages] of Object.entries(this.groupedMessages)) {\n const directoryPath = path.join(this.storagePath, key);\n fs.mkdirSync(directoryPath, { recursive: true });\n const filePath = path.join(directoryPath, `${this.fileName}.${this.extension}`);\n\n let fileContents = { messages: [] as any[] };\n if (fs.existsSync(filePath)) {\n try {\n fileContents = JSON.parse(fs.readFileSync(filePath, \"utf-8\"));\n if (!Array.isArray(fileContents.messages)) fileContents.messages = [];\n } catch (e) {\n fileContents = { messages: [] };\n }\n }\n fileContents.messages.push(...groupMessages);\n fs.writeFileSync(filePath, safeJsonStringify(fileContents, 2));\n }\n } else {\n fs.mkdirSync(this.storagePath, { recursive: true });\n let fileContents = { messages: [] as any[] };\n if (fs.existsSync(this.filePath)) {\n try {\n fileContents = JSON.parse(fs.readFileSync(this.filePath, \"utf-8\"));\n if (!Array.isArray(fileContents.messages)) fileContents.messages = [];\n } catch (e) {\n fileContents = { messages: [] };\n }\n }\n fileContents.messages.push(...this.messages);\n fs.writeFileSync(this.filePath, safeJsonStringify(fileContents, 2));\n }\n\n this.onSave();\n }\n\n /**\n * {@inheritdoc}\n */\n public async log(data: LoggingData) {\n let stack: string[] | undefined;\n\n if (data.message instanceof Error) {\n stack = data.message.stack?.split(\"\\n\");\n data.message = data.message.message;\n }\n\n const { module, action, message, type: level, context } = data;\n\n if (!this.shouldBeLogged(data)) return;\n\n const { date: dateFormat, time } = this.getDateAndTimeFormat();\n\n const date = dayjs().format(dateFormat + \" \" + time);\n\n this.messages.push({\n content: message,\n level,\n date,\n module,\n action,\n stack,\n context,\n timestamp: new Date().toISOString(),\n } as LogMessage);\n\n await this.checkIfMessagesShouldBeWritten(); // Immediate check on buffer size\n }\n\n /**\n * Write messages to the file\n */\n protected async writeMessagesToFile(): Promise<void> {\n if (this.messages.length === 0 || this.isWriting || !this.isInitialized) return;\n\n this.isWriting = true;\n\n if (this.messagedShouldBeGrouped) {\n return await this.writeGroupedMessagesToFile();\n }\n\n await this.checkAndRotateFile(); // Ensure file rotation is handled\n\n let fileContents = { messages: [] as any[] };\n\n if (await fileExistsAsync(this.filePath)) {\n try {\n fileContents = (await getJsonFileAsync(this.filePath)) as { messages: any[] };\n } catch (error) {\n console.error(\"Error reading log file, reinitializing:\", error);\n fileContents = { messages: [] }; // Reinitialize the file if corrupted\n }\n } else {\n fileContents = { messages: [] }; // Reinitialize the file if corrupted\n }\n\n fileContents.messages.push(...this.messages);\n\n try {\n await fs.promises.writeFile(this.filePath, safeJsonStringify(fileContents, 2));\n\n this.onSave();\n } catch (error) {\n console.error(\"Failed to write log:\", error);\n // Implement fallback logic here\n this.isWriting = false;\n }\n }\n\n /**\n * Write grouped messages to the file\n */\n protected async writeGroupedMessagesToFile(): Promise<void> {\n // first step, is to group the messages\n this.prepareGroupedMessages();\n\n // now each key in the grouped messages, represents the directory path that should extend the storage path\n for (const [key, groupMessages] of Object.entries(this.groupedMessages)) {\n const directoryPath = path.join(this.storagePath, key);\n\n await ensureDirectoryAsync(directoryPath);\n\n const filePath = path.join(directoryPath, `${this.fileName}.${this.extension}`);\n\n await this.checkAndRotateFile(filePath); // Ensure we check file size before writing\n\n let fileContents: { messages: any[] } = { messages: [] };\n if (await fileExistsAsync(filePath)) {\n try {\n fileContents = (await getJsonFileAsync(filePath)) as { messages: any[] };\n } catch (error) {\n console.error(\"Error reading log file, reinitializing:\", error);\n fileContents = { messages: [] };\n }\n } else {\n fileContents = { messages: [] };\n }\n\n fileContents.messages.push(...groupMessages);\n\n try {\n await fs.promises.writeFile(filePath, safeJsonStringify(fileContents, 2));\n } catch (error) {\n console.error(\"Failed to write log:\", error);\n this.isWriting = false;\n }\n }\n\n this.onSave();\n }\n}\n"],"mappings":";;;;;;;;AAQA,IAAa,cAAb,cAAiC,QAA+B;;;cAIhD;;;;;CAKd,IAAW,YAAoB;EAC7B,OAAO;CACT;;;;CAKA,AAAO,YAAkB;EACvB,IAAI,KAAK,SAAS,WAAW,KAAK,OAAO,KAAK,KAAK,eAAe,CAAC,CAAC,WAAW,GAAG;EAElF,IAAI,KAAK,yBAAyB;GAChC,KAAK,uBAAuB;GAM5B,KAAK,MAAM,CAAC,KAAK,kBAAkB,OAAO,QAAQ,KAAK,eAAe,GAAG;IACvE,MAAM,gBAAgB,KAAK,KAAK,KAAK,aAAa,GAAG;IACrD,GAAG,UAAU,eAAe,EAAE,WAAW,KAAK,CAAC;IAC/C,MAAM,WAAW,KAAK,KAAK,eAAe,GAAG,KAAK,SAAS,GAAG,KAAK,WAAW;IAE9E,IAAI,eAAe,EAAE,UAAU,CAAC,EAAW;IAC3C,IAAI,GAAG,WAAW,QAAQ,GACxB,IAAI;KACF,eAAe,KAAK,MAAM,GAAG,aAAa,UAAU,OAAO,CAAC;KAC5D,IAAI,CAAC,MAAM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,aAAa;GAE3C,IAAI;IACF,MAAM,GAAG,SAAS,UAAU,UAAU,kBAAkB,cAAc,CAAC,CAAC;GAC1E,SAAS,OAAO;IACd,QAAQ,MAAM,wBAAwB,KAAK;IAC3C,KAAK,YAAY;GACnB;EACF;EAEA,KAAK,OAAO;CACd;AACF"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { BasicLogConfigurations, LogLevel, LoggingData } from "../types.mjs";
|
|
2
2
|
import { LogChannel } from "../log-channel.mjs";
|
|
3
3
|
|
|
4
|
-
//#region
|
|
4
|
+
//#region ../../packages/logger/src/channels/sentry-log.d.ts
|
|
5
5
|
/**
|
|
6
6
|
* Sentry severity levels — the `@sentry/node` `SeverityLevel` union.
|
|
7
7
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sentry-log.d.mts","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"sentry-log.d.mts","names":[],"sources":["../../../../../../../../packages/logger/src/channels/sentry-log.ts"],"mappings":";;;;;;AAC8E;KAgBzE,mBAAA;;;AAAmB;UAWP,eAAA;EACf,QAAA,CAAS,KAAA,EAAO,mBAAA;EAChB,OAAA,CAAQ,IAAA,EAAM,MAAA;EACd,UAAA,CAAW,IAAA,UAAc,OAAA,EAAS,MAAA;AAAA;;;;KAMxB,gBAAA;EACV,QAAA;EACA,OAAA;EACA,KAAA,GAAQ,mBAAA;EACR,IAAA,GAAO,MAAM;AAAA;;;;;;UAQE,eAAA;EACf,gBAAA,CAAiB,SAAA;EACjB,cAAA,CAAe,OAAA,UAAiB,KAAA,GAAQ,mBAAA;EACxC,aAAA,CAAc,UAAA,EAAY,gBAAA;EAC1B,SAAA,CAAU,QAAA,GAAW,KAAA,EAAO,eAAA;EAC5B,KAAA,CAAM,OAAA,YAAmB,OAAA;AAAA;;;;;;KAQf,iBAAA;EACV,GAAA;EACA,WAAA;EACA,OAAA;EACA,UAAA;EAAA,CACC,GAAA;AAAA;AAAA,KAyDS,eAAA,GAAkB,sBAAA;EAtEI;;;;;EA4EhC,MAAA,GAAS,eAAA;EA/E+B;;;;;EAqFxC,OAAA,GAAU,iBAAA;EAnFkB;;;;;;;EA2F5B,WAAA,GAAc,QAAA;EAlFJ;;;;;EAwFV,YAAA;AAAA;;;;AAnFY;AAyDd;;;;;;;;;;;;;;;;;;AA0Bc;AA2Bd;cAAa,SAAA,SAAkB,UAAA,CAAW,eAAA;;;;EAIjC,IAAA;EAqDiB;;;EAhDjB,WAAA;EATsB;;;EAAA,UAenB,qBAAA,EAAuB,eAAA;EAfO;;;;;EAAA,QAyBhC,MAAA;EAMA;;;;EAAA,QAAA,aAAA;EA0BgB;;;;;;;cAjBL,cAAA,GAAiB,eAAA;EAmH5B;;;;;AAiEgB;;EAjEhB,UAlGQ,IAAA,IAAQ,OAAA;;;;EA2BX,GAAA,CAAI,IAAA,EAAM,WAAA,GAAc,OAAA;;;;;EAiDxB,KAAA,IAAS,OAAA;;;;UAWd,YAAA;;;;;;;;UAWA,YAAA;;;;;UAiCA,aAAA;;;;;UAeA,MAAA;;;;;;UAiBA,gBAAA;AAAA"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { LogChannel } from "../log-channel.mjs";
|
|
2
2
|
import { safeJsonStringify } from "../utils/safe-json-stringify.mjs";
|
|
3
3
|
|
|
4
|
-
//#region
|
|
4
|
+
//#region ../../packages/logger/src/channels/sentry-log.ts
|
|
5
5
|
let Sentry;
|
|
6
6
|
let isModuleExists = null;
|
|
7
7
|
let loadingPromise;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sentry-log.mjs","names":[],"sources":["../../../../../../../logger/src/channels/sentry-log.ts"],"sourcesContent":["import { LogChannel } from \"../log-channel\";\nimport type { BasicLogConfigurations, LoggingData, LogLevel } from \"../types\";\nimport { safeJsonStringify } from \"../utils/safe-json-stringify\";\n\n// ── @sentry/node as an optional peer ─────────────────────────────────────────\n// @sentry/node is referenced ONLY through the local minimal types below — never\n// via `typeof import(\"@sentry/node\")`. This package is served as source\n// (`main` → `./src/index.ts`), so its `.ts` becomes part of a consumer's TS\n// program; a static type reference to the SDK would force module resolution and\n// break every consumer who (correctly) never installs the optional peer with a\n// TS2307 \"cannot find module\". The runtime import uses an indirect specifier for\n// the same reason, and its result is cast to these shapes. The shapes mirror the\n// stable `@sentry/node` public API (unchanged across v8–v10).\n\n/**\n * Sentry severity levels — the `@sentry/node` `SeverityLevel` union.\n */\ntype SentrySeverityLevel =\n | \"fatal\"\n | \"error\"\n | \"warning\"\n | \"log\"\n | \"info\"\n | \"debug\";\n\n/**\n * The Sentry `Scope` surface used while building a single event.\n */\nexport interface SentryScopeLike {\n setLevel(level: SentrySeverityLevel): void;\n setTags(tags: Record<string, string>): void;\n setContext(name: string, context: Record<string, unknown> | null): void;\n}\n\n/**\n * A Sentry breadcrumb, as passed to `addBreadcrumb`.\n */\nexport type SentryBreadcrumb = {\n category?: string;\n message?: string;\n level?: SentrySeverityLevel;\n data?: Record<string, unknown>;\n};\n\n/**\n * The subset of the `@sentry/node` API `SentryLog` calls. The `@sentry/node`\n * namespace satisfies this shape, so an app can pass it straight through as\n * `client`; a test (or a custom forwarder) can supply a compatible stand-in.\n */\nexport interface SentryForwarder {\n captureException(exception: unknown): string;\n captureMessage(message: string, level?: SentrySeverityLevel): string;\n addBreadcrumb(breadcrumb: SentryBreadcrumb): void;\n withScope(callback: (scope: SentryScopeLike) => void): void;\n flush(timeout?: number): Promise<boolean>;\n}\n\n/**\n * Sentry initialization options. Mirrors the common `@sentry/node` `NodeOptions`\n * fields; the index signature keeps any other SDK option valid without coupling\n * to the SDK's types.\n */\nexport type SentryInitOptions = {\n dsn?: string;\n environment?: string;\n release?: string;\n sampleRate?: number;\n [key: string]: unknown;\n};\n\n/**\n * The lazily-imported `@sentry/node` namespace surface — the forwarder plus the\n * lifecycle calls the channel uses when it owns initialization.\n */\ninterface SentryNamespace extends SentryForwarder {\n init(options?: SentryInitOptions): unknown;\n getClient(): unknown;\n}\n\nlet Sentry: SentryNamespace | undefined;\nlet isModuleExists: boolean | null = null;\nlet loadingPromise: Promise<void> | undefined;\n\nconst SENTRY_INSTALL_INSTRUCTIONS = `\nThe Sentry log channel requires the @sentry/node package.\nInstall it with:\n\n npm install @sentry/node\n\nOr with your preferred package manager:\n\n pnpm add @sentry/node\n yarn add @sentry/node\n`.trim();\n\n/**\n * Load @sentry/node once, lazily and concurrency-safely. A bare catch maps any\n * import failure to \"not installed\" — the curated install message surfaces at\n * `log()` time, never as a boot-time module-resolution crash.\n */\nfunction loadSentry(): Promise<void> {\n if (isModuleExists !== null) {\n return Promise.resolve();\n }\n\n if (loadingPromise) {\n return loadingPromise;\n }\n\n loadingPromise = (async () => {\n try {\n // Indirect specifier (typed `string`, not a literal) so TypeScript never\n // statically resolves the optional peer — see the file header.\n const sentryModule: string = \"@sentry/node\";\n Sentry = (await import(sentryModule)) as unknown as SentryNamespace;\n isModuleExists = true;\n } catch {\n isModuleExists = false;\n }\n })();\n\n return loadingPromise;\n}\n\nexport type SentryLogConfig = BasicLogConfigurations & {\n /**\n * Reuse an already-initialized Sentry instance — typically the `@sentry/node`\n * namespace from an app that already calls `Sentry.init(...)`. When set, the\n * channel forwards through it and never imports or re-initializes the SDK.\n */\n client?: SentryForwarder;\n /**\n * Initialize Sentry from these options instead of reusing a host client. The\n * channel lazily imports `@sentry/node` and calls `Sentry.init(options)` once,\n * guarded so it never clobbers an existing client.\n */\n options?: SentryInitOptions;\n /**\n * Levels delivered as Sentry *events* (these consume the error quota). Every\n * other level is recorded as a breadcrumb that rides along with the next\n * event, costing no quota.\n *\n * @default [\"fatal\", \"error\", \"warn\"]\n */\n eventLevels?: LogLevel[];\n /**\n * Milliseconds `flush()` waits for the transport to drain on shutdown.\n *\n * @default 2000\n */\n flushTimeout?: number;\n};\n\n/**\n * Forwards log entries to Sentry.\n *\n * Entries at an `eventLevels` level (`error` / `warn` by default) become Sentry\n * **events**: an `Error` message via `captureException` (preserving the real\n * stack), any other message via `captureMessage`. Every other level becomes a\n * **breadcrumb** — buffered and attached to the next event, consuming no error\n * quota. `module` / `action` are attached as searchable tags and the entry's\n * `context` as a structured Sentry context.\n *\n * The SDK is an optional peer: pass an existing `client` (reused as-is) or\n * `options` (the channel lazily imports `@sentry/node` and initializes it). On\n * graceful shutdown, `await log.flush()` drains pending events via\n * `Sentry.flush(timeout)`.\n *\n * @example\n * // Existing app — reuse the initialized Sentry client\n * import * as Sentry from \"@sentry/node\";\n * log.addChannel(new SentryLog({ client: Sentry }));\n *\n * @example\n * // New app — let the channel initialize Sentry\n * log.addChannel(new SentryLog({ options: { dsn: process.env.SENTRY_DSN } }));\n */\nexport class SentryLog extends LogChannel<SentryLogConfig> {\n /**\n * {@inheritdoc}\n */\n public name = \"sentry\";\n\n /**\n * {@inheritdoc}\n */\n public description =\n \"Forwards entries to Sentry as events (error/warn) or breadcrumbs (everything else)\";\n\n /**\n * {@inheritdoc}\n */\n protected defaultConfigurations: SentryLogConfig = {\n eventLevels: [\"fatal\", \"error\", \"warn\"],\n flushTimeout: 2_000,\n };\n\n /**\n * The resolved forwarder — the injected `client` or the lazily-imported\n * `@sentry/node` namespace. `undefined` until `init()` resolves, and when the\n * SDK is absent (then `log()` surfaces the install message once).\n */\n private sentry?: SentryForwarder;\n\n /**\n * Guards the one-time \"@sentry/node is not installed\" notice so a missing SDK\n * doesn't spam stderr on every entry.\n */\n private warnedMissing = false;\n\n /**\n * Resolve an injected `client` (the Sentry namespace) **synchronously**, so an\n * entry logged on the same tick as construction — e.g. at app boot, before\n * the base schedules `init()` on the next tick via `setTimeout(0)` — is not\n * silently dropped. The `options` (lazy-import) path is inherently async and\n * still resolves in `init()`.\n */\n public constructor(configurations?: SentryLogConfig) {\n super(configurations);\n\n const injected = this.config(\"client\");\n\n if (injected) {\n this.sentry = injected;\n }\n }\n\n /**\n * Resolve the forwarder: reuse the injected client, otherwise lazily import\n * `@sentry/node` and (only when explicit `options` are supplied and no client\n * exists yet) initialize it. Never throws — the base runs `init()` inside an\n * un-awaited `setTimeout`, so a throw would become an unhandled rejection and\n * `isInitialized` would never flip; a missing SDK is reported from `log()`.\n */\n protected async init(): Promise<void> {\n const injected = this.config(\"client\");\n\n if (injected) {\n this.sentry = injected;\n\n return;\n }\n\n await loadSentry();\n\n if (!Sentry) {\n return;\n }\n\n const options = this.config(\"options\");\n\n if (options && !Sentry.getClient()) {\n Sentry.init(options);\n }\n\n this.sentry = Sentry;\n }\n\n /**\n * {@inheritdoc}\n */\n public async log(data: LoggingData): Promise<void> {\n if (!this.shouldBeLogged(data)) {\n return;\n }\n\n // Only wait for the optional SDK when we do not already have a forwarder.\n // An INJECTED client is resolved synchronously in the constructor, and that is\n // the whole point of doing it there: an entry logged on the same tick as\n // construction must still send. Awaiting loadSentry() unconditionally undid\n // that — with @sentry/node absent (it is an optional peer) the import can take\n // seconds, so a log with a perfectly good injected client stalled behind an SDK\n // it was never going to use.\n if (!this.sentry && isModuleExists === null) {\n // wait until module is fully loaded\n await loadSentry();\n }\n\n if (!this.sentry) {\n this.reportMissingSdk();\n\n return;\n }\n\n const { module, action, message, type: level, context } = data;\n\n if (this.isEventLevel(level)) {\n this.captureEvent(this.sentry, {\n module,\n action,\n message,\n level,\n context,\n });\n\n return;\n }\n\n this.sentry.addBreadcrumb({\n category: module,\n message: this.toText(message),\n level: this.toSentryLevel(level),\n data: context,\n });\n }\n\n /**\n * Drain pending Sentry events. Bounded by `flushTimeout` so an unreachable\n * Sentry can never hang a graceful shutdown. No-op when the SDK is absent.\n */\n public async flush(): Promise<void> {\n if (!this.sentry) {\n return;\n }\n\n await this.sentry.flush(this.config(\"flushTimeout\"));\n }\n\n /**\n * Whether the level should be sent as a Sentry event (vs a breadcrumb).\n */\n private isEventLevel(level: LogLevel): boolean {\n return Boolean(this.config(\"eventLevels\")?.includes(level));\n }\n\n /**\n * Send an entry as a Sentry event. An `Error` message goes through\n * `captureException` so Sentry parses the real stack and groups properly;\n * any other message goes through `captureMessage`. `module` / `action` are\n * attached as tags and `context` as a structured context, scoped to this\n * event only via `withScope`.\n */\n private captureEvent(\n sentry: SentryForwarder,\n entry: {\n module: string;\n action: string;\n message: unknown;\n level: LogLevel;\n context?: Record<string, any>;\n },\n ): void {\n const { module, action, message, level, context } = entry;\n const sentryLevel = this.toSentryLevel(level);\n\n sentry.withScope((scope) => {\n scope.setLevel(sentryLevel);\n scope.setTags({ module, action });\n\n if (context) {\n scope.setContext(\"context\", context);\n }\n\n if (message instanceof Error) {\n sentry.captureException(message);\n } else {\n sentry.captureMessage(this.toText(message), sentryLevel);\n }\n });\n }\n\n /**\n * Map a logger level to a Sentry severity. `success` has no Sentry\n * equivalent, so it is reported as informational.\n */\n private toSentryLevel(level: LogLevel): SentrySeverityLevel {\n switch (level) {\n case \"warn\":\n return \"warning\";\n case \"success\":\n return \"info\";\n default:\n return level; // debug | info | error | fatal map 1:1\n }\n }\n\n /**\n * Coerce a message into the string Sentry's APIs expect — an `Error`'s\n * `.message`, a string as-is, anything else safely JSON-serialized.\n */\n private toText(message: unknown): string {\n if (typeof message === \"string\") {\n return message;\n }\n\n if (message instanceof Error) {\n return message.message;\n }\n\n return safeJsonStringify(message);\n }\n\n /**\n * Surface the install instructions exactly once when the SDK is absent. The\n * logger can't log through itself here, so this writes to stderr — matching\n * how the file channels report write failures.\n */\n private reportMissingSdk(): void {\n if (isModuleExists === false && !this.warnedMissing) {\n this.warnedMissing = true;\n console.error(SENTRY_INSTALL_INSTRUCTIONS);\n }\n }\n}\n"],"mappings":";;;;AA+EA,IAAI;AACJ,IAAI,iBAAiC;AACrC,IAAI;AAEJ,MAAM,8BAA8B;;;;;;;;;;EAUlC,KAAK;;;;;;AAOP,SAAS,aAA4B;CACnC,IAAI,mBAAmB,MACrB,OAAO,QAAQ,QAAQ;CAGzB,IAAI,gBACF,OAAO;CAGT,kBAAkB,YAAY;EAC5B,IAAI;GAIF,SAAU,MAAM,OAAO;GACvB,iBAAiB;EACnB,QAAQ;GACN,iBAAiB;EACnB;CACF,EAAC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KAAK,OAAO,aAAa,CAAC,EAAE,SAAS,KAAK,CAAC;CAC5D;;;;;;;;CASA,AAAQ,aACN,QACA,OAOM;EACN,MAAM,EAAE,QAAQ,QAAQ,SAAS,OAAO,YAAY;EACpD,MAAM,cAAc,KAAK,cAAc,KAAK;EAE5C,OAAO,WAAW,UAAU;GAC1B,MAAM,SAAS,WAAW;GAC1B,MAAM,QAAQ;IAAE;IAAQ;GAAO,CAAC;GAEhC,IAAI,SACF,MAAM,WAAW,WAAW,OAAO;GAGrC,IAAI,mBAAmB,OACrB,OAAO,iBAAiB,OAAO;QAE/B,OAAO,eAAe,KAAK,OAAO,OAAO,GAAG,WAAW;EAE3D,CAAC;CACH;;;;;CAMA,AAAQ,cAAc,OAAsC;EAC1D,QAAQ,OAAR;GACE,KAAK,QACH,OAAO;GACT,KAAK,WACH,OAAO;GACT,SACE,OAAO;EACX;CACF;;;;;CAMA,AAAQ,OAAO,SAA0B;EACvC,IAAI,OAAO,YAAY,UACrB,OAAO;EAGT,IAAI,mBAAmB,OACrB,OAAO,QAAQ;EAGjB,OAAO,kBAAkB,OAAO;CAClC;;;;;;CAOA,AAAQ,mBAAyB;EAC/B,IAAI,mBAAmB,SAAS,CAAC,KAAK,eAAe;GACnD,KAAK,gBAAgB;GACrB,QAAQ,MAAM,2BAA2B;EAC3C;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"sentry-log.mjs","names":[],"sources":["../../../../../../../../packages/logger/src/channels/sentry-log.ts"],"sourcesContent":["import { LogChannel } from \"../log-channel\";\nimport type { BasicLogConfigurations, LoggingData, LogLevel } from \"../types\";\nimport { safeJsonStringify } from \"../utils/safe-json-stringify\";\n\n// ── @sentry/node as an optional peer ─────────────────────────────────────────\n// @sentry/node is referenced ONLY through the local minimal types below — never\n// via `typeof import(\"@sentry/node\")`. This package is served as source\n// (`main` → `./src/index.ts`), so its `.ts` becomes part of a consumer's TS\n// program; a static type reference to the SDK would force module resolution and\n// break every consumer who (correctly) never installs the optional peer with a\n// TS2307 \"cannot find module\". The runtime import uses an indirect specifier for\n// the same reason, and its result is cast to these shapes. The shapes mirror the\n// stable `@sentry/node` public API (unchanged across v8–v10).\n\n/**\n * Sentry severity levels — the `@sentry/node` `SeverityLevel` union.\n */\ntype SentrySeverityLevel =\n | \"fatal\"\n | \"error\"\n | \"warning\"\n | \"log\"\n | \"info\"\n | \"debug\";\n\n/**\n * The Sentry `Scope` surface used while building a single event.\n */\nexport interface SentryScopeLike {\n setLevel(level: SentrySeverityLevel): void;\n setTags(tags: Record<string, string>): void;\n setContext(name: string, context: Record<string, unknown> | null): void;\n}\n\n/**\n * A Sentry breadcrumb, as passed to `addBreadcrumb`.\n */\nexport type SentryBreadcrumb = {\n category?: string;\n message?: string;\n level?: SentrySeverityLevel;\n data?: Record<string, unknown>;\n};\n\n/**\n * The subset of the `@sentry/node` API `SentryLog` calls. The `@sentry/node`\n * namespace satisfies this shape, so an app can pass it straight through as\n * `client`; a test (or a custom forwarder) can supply a compatible stand-in.\n */\nexport interface SentryForwarder {\n captureException(exception: unknown): string;\n captureMessage(message: string, level?: SentrySeverityLevel): string;\n addBreadcrumb(breadcrumb: SentryBreadcrumb): void;\n withScope(callback: (scope: SentryScopeLike) => void): void;\n flush(timeout?: number): Promise<boolean>;\n}\n\n/**\n * Sentry initialization options. Mirrors the common `@sentry/node` `NodeOptions`\n * fields; the index signature keeps any other SDK option valid without coupling\n * to the SDK's types.\n */\nexport type SentryInitOptions = {\n dsn?: string;\n environment?: string;\n release?: string;\n sampleRate?: number;\n [key: string]: unknown;\n};\n\n/**\n * The lazily-imported `@sentry/node` namespace surface — the forwarder plus the\n * lifecycle calls the channel uses when it owns initialization.\n */\ninterface SentryNamespace extends SentryForwarder {\n init(options?: SentryInitOptions): unknown;\n getClient(): unknown;\n}\n\nlet Sentry: SentryNamespace | undefined;\nlet isModuleExists: boolean | null = null;\nlet loadingPromise: Promise<void> | undefined;\n\nconst SENTRY_INSTALL_INSTRUCTIONS = `\nThe Sentry log channel requires the @sentry/node package.\nInstall it with:\n\n npm install @sentry/node\n\nOr with your preferred package manager:\n\n pnpm add @sentry/node\n yarn add @sentry/node\n`.trim();\n\n/**\n * Load @sentry/node once, lazily and concurrency-safely. A bare catch maps any\n * import failure to \"not installed\" — the curated install message surfaces at\n * `log()` time, never as a boot-time module-resolution crash.\n */\nfunction loadSentry(): Promise<void> {\n if (isModuleExists !== null) {\n return Promise.resolve();\n }\n\n if (loadingPromise) {\n return loadingPromise;\n }\n\n loadingPromise = (async () => {\n try {\n // Indirect specifier (typed `string`, not a literal) so TypeScript never\n // statically resolves the optional peer — see the file header.\n const sentryModule: string = \"@sentry/node\";\n Sentry = (await import(sentryModule)) as unknown as SentryNamespace;\n isModuleExists = true;\n } catch {\n isModuleExists = false;\n }\n })();\n\n return loadingPromise;\n}\n\nexport type SentryLogConfig = BasicLogConfigurations & {\n /**\n * Reuse an already-initialized Sentry instance — typically the `@sentry/node`\n * namespace from an app that already calls `Sentry.init(...)`. When set, the\n * channel forwards through it and never imports or re-initializes the SDK.\n */\n client?: SentryForwarder;\n /**\n * Initialize Sentry from these options instead of reusing a host client. The\n * channel lazily imports `@sentry/node` and calls `Sentry.init(options)` once,\n * guarded so it never clobbers an existing client.\n */\n options?: SentryInitOptions;\n /**\n * Levels delivered as Sentry *events* (these consume the error quota). Every\n * other level is recorded as a breadcrumb that rides along with the next\n * event, costing no quota.\n *\n * @default [\"fatal\", \"error\", \"warn\"]\n */\n eventLevels?: LogLevel[];\n /**\n * Milliseconds `flush()` waits for the transport to drain on shutdown.\n *\n * @default 2000\n */\n flushTimeout?: number;\n};\n\n/**\n * Forwards log entries to Sentry.\n *\n * Entries at an `eventLevels` level (`error` / `warn` by default) become Sentry\n * **events**: an `Error` message via `captureException` (preserving the real\n * stack), any other message via `captureMessage`. Every other level becomes a\n * **breadcrumb** — buffered and attached to the next event, consuming no error\n * quota. `module` / `action` are attached as searchable tags and the entry's\n * `context` as a structured Sentry context.\n *\n * The SDK is an optional peer: pass an existing `client` (reused as-is) or\n * `options` (the channel lazily imports `@sentry/node` and initializes it). On\n * graceful shutdown, `await log.flush()` drains pending events via\n * `Sentry.flush(timeout)`.\n *\n * @example\n * // Existing app — reuse the initialized Sentry client\n * import * as Sentry from \"@sentry/node\";\n * log.addChannel(new SentryLog({ client: Sentry }));\n *\n * @example\n * // New app — let the channel initialize Sentry\n * log.addChannel(new SentryLog({ options: { dsn: process.env.SENTRY_DSN } }));\n */\nexport class SentryLog extends LogChannel<SentryLogConfig> {\n /**\n * {@inheritdoc}\n */\n public name = \"sentry\";\n\n /**\n * {@inheritdoc}\n */\n public description =\n \"Forwards entries to Sentry as events (error/warn) or breadcrumbs (everything else)\";\n\n /**\n * {@inheritdoc}\n */\n protected defaultConfigurations: SentryLogConfig = {\n eventLevels: [\"fatal\", \"error\", \"warn\"],\n flushTimeout: 2_000,\n };\n\n /**\n * The resolved forwarder — the injected `client` or the lazily-imported\n * `@sentry/node` namespace. `undefined` until `init()` resolves, and when the\n * SDK is absent (then `log()` surfaces the install message once).\n */\n private sentry?: SentryForwarder;\n\n /**\n * Guards the one-time \"@sentry/node is not installed\" notice so a missing SDK\n * doesn't spam stderr on every entry.\n */\n private warnedMissing = false;\n\n /**\n * Resolve an injected `client` (the Sentry namespace) **synchronously**, so an\n * entry logged on the same tick as construction — e.g. at app boot, before\n * the base schedules `init()` on the next tick via `setTimeout(0)` — is not\n * silently dropped. The `options` (lazy-import) path is inherently async and\n * still resolves in `init()`.\n */\n public constructor(configurations?: SentryLogConfig) {\n super(configurations);\n\n const injected = this.config(\"client\");\n\n if (injected) {\n this.sentry = injected;\n }\n }\n\n /**\n * Resolve the forwarder: reuse the injected client, otherwise lazily import\n * `@sentry/node` and (only when explicit `options` are supplied and no client\n * exists yet) initialize it. Never throws — the base runs `init()` inside an\n * un-awaited `setTimeout`, so a throw would become an unhandled rejection and\n * `isInitialized` would never flip; a missing SDK is reported from `log()`.\n */\n protected async init(): Promise<void> {\n const injected = this.config(\"client\");\n\n if (injected) {\n this.sentry = injected;\n\n return;\n }\n\n await loadSentry();\n\n if (!Sentry) {\n return;\n }\n\n const options = this.config(\"options\");\n\n if (options && !Sentry.getClient()) {\n Sentry.init(options);\n }\n\n this.sentry = Sentry;\n }\n\n /**\n * {@inheritdoc}\n */\n public async log(data: LoggingData): Promise<void> {\n if (!this.shouldBeLogged(data)) {\n return;\n }\n\n // Only wait for the optional SDK when we do not already have a forwarder.\n // An INJECTED client is resolved synchronously in the constructor, and that is\n // the whole point of doing it there: an entry logged on the same tick as\n // construction must still send. Awaiting loadSentry() unconditionally undid\n // that — with @sentry/node absent (it is an optional peer) the import can take\n // seconds, so a log with a perfectly good injected client stalled behind an SDK\n // it was never going to use.\n if (!this.sentry && isModuleExists === null) {\n // wait until module is fully loaded\n await loadSentry();\n }\n\n if (!this.sentry) {\n this.reportMissingSdk();\n\n return;\n }\n\n const { module, action, message, type: level, context } = data;\n\n if (this.isEventLevel(level)) {\n this.captureEvent(this.sentry, {\n module,\n action,\n message,\n level,\n context,\n });\n\n return;\n }\n\n this.sentry.addBreadcrumb({\n category: module,\n message: this.toText(message),\n level: this.toSentryLevel(level),\n data: context,\n });\n }\n\n /**\n * Drain pending Sentry events. Bounded by `flushTimeout` so an unreachable\n * Sentry can never hang a graceful shutdown. No-op when the SDK is absent.\n */\n public async flush(): Promise<void> {\n if (!this.sentry) {\n return;\n }\n\n await this.sentry.flush(this.config(\"flushTimeout\"));\n }\n\n /**\n * Whether the level should be sent as a Sentry event (vs a breadcrumb).\n */\n private isEventLevel(level: LogLevel): boolean {\n return Boolean(this.config(\"eventLevels\")?.includes(level));\n }\n\n /**\n * Send an entry as a Sentry event. An `Error` message goes through\n * `captureException` so Sentry parses the real stack and groups properly;\n * any other message goes through `captureMessage`. `module` / `action` are\n * attached as tags and `context` as a structured context, scoped to this\n * event only via `withScope`.\n */\n private captureEvent(\n sentry: SentryForwarder,\n entry: {\n module: string;\n action: string;\n message: unknown;\n level: LogLevel;\n context?: Record<string, any>;\n },\n ): void {\n const { module, action, message, level, context } = entry;\n const sentryLevel = this.toSentryLevel(level);\n\n sentry.withScope((scope) => {\n scope.setLevel(sentryLevel);\n scope.setTags({ module, action });\n\n if (context) {\n scope.setContext(\"context\", context);\n }\n\n if (message instanceof Error) {\n sentry.captureException(message);\n } else {\n sentry.captureMessage(this.toText(message), sentryLevel);\n }\n });\n }\n\n /**\n * Map a logger level to a Sentry severity. `success` has no Sentry\n * equivalent, so it is reported as informational.\n */\n private toSentryLevel(level: LogLevel): SentrySeverityLevel {\n switch (level) {\n case \"warn\":\n return \"warning\";\n case \"success\":\n return \"info\";\n default:\n return level; // debug | info | error | fatal map 1:1\n }\n }\n\n /**\n * Coerce a message into the string Sentry's APIs expect — an `Error`'s\n * `.message`, a string as-is, anything else safely JSON-serialized.\n */\n private toText(message: unknown): string {\n if (typeof message === \"string\") {\n return message;\n }\n\n if (message instanceof Error) {\n return message.message;\n }\n\n return safeJsonStringify(message);\n }\n\n /**\n * Surface the install instructions exactly once when the SDK is absent. The\n * logger can't log through itself here, so this writes to stderr — matching\n * how the file channels report write failures.\n */\n private reportMissingSdk(): void {\n if (isModuleExists === false && !this.warnedMissing) {\n this.warnedMissing = true;\n console.error(SENTRY_INSTALL_INSTRUCTIONS);\n }\n }\n}\n"],"mappings":";;;;AA+EA,IAAI;AACJ,IAAI,iBAAiC;AACrC,IAAI;AAEJ,MAAM,8BAA8B;;;;;;;;;;EAUlC,KAAK;;;;;;AAOP,SAAS,aAA4B;CACnC,IAAI,mBAAmB,MACrB,OAAO,QAAQ,QAAQ;CAGzB,IAAI,gBACF,OAAO;CAGT,kBAAkB,YAAY;EAC5B,IAAI;GAIF,SAAU,MAAM,OAAO;GACvB,iBAAiB;EACnB,QAAQ;GACN,iBAAiB;EACnB;CACF,EAAC,CAAE;CAEH,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;AAuDA,IAAa,YAAb,cAA+B,WAA4B;;;;;;;;CAwCzD,AAAO,YAAY,gBAAkC;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AAS,OAAO,YAAY;EACpD,MAAM,cAAc,KAAK,cAAc,KAAK;EAE5C,OAAO,WAAW,UAAU;GAC1B,MAAM,SAAS,WAAW;GAC1B,MAAM,QAAQ;IAAE;IAAQ;GAAO,CAAC;GAEhC,IAAI,SACF,MAAM,WAAW,WAAW,OAAO;GAGrC,IAAI,mBAAmB,OACrB,OAAO,iBAAiB,OAAO;QAE/B,OAAO,eAAe,KAAK,OAAO,OAAO,GAAG,WAAW;EAE3D,CAAC;CACH;;;;;CAMA,AAAQ,cAAc,OAAsC;EAC1D,QAAQ,OAAR;GACE,KAAK,QACH,OAAO;GACT,KAAK,WACH,OAAO;GACT,SACE,OAAO;EACX;CACF;;;;;CAMA,AAAQ,OAAO,SAA0B;EACvC,IAAI,OAAO,YAAY,UACrB,OAAO;EAGT,IAAI,mBAAmB,OACrB,OAAO,QAAQ;EAGjB,OAAO,kBAAkB,OAAO;CAClC;;;;;;CAOA,AAAQ,mBAAyB;EAC/B,IAAI,mBAAmB,SAAS,CAAC,KAAK,eAAe;GACnD,KAAK,gBAAgB;GACrB,QAAQ,MAAM,2BAA2B;EAC3C;CACF;AACF"}
|
package/esm/index.d.mts
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
|
-
import { AutoFlushEvent, BasicLogConfigurations, DebugMode, LogContract, LogLevel, LogMessage, LoggingData, OmittedLoggingData, RedactCensor, RedactConfig } from "./types.mjs";
|
|
1
|
+
import { AutoFlushEvent, BasicLogConfigurations, ChannelErrorHandler, DebugMode, LogContract, LogLevel, LogMessage, LoggingData, OmittedLoggingData, RedactCensor, RedactConfig } from "./types.mjs";
|
|
2
2
|
import { LogChannel } from "./log-channel.mjs";
|
|
3
3
|
import { ConsoleLog, ConsoleLogConfig } from "./channels/console-log.mjs";
|
|
4
4
|
import { FileLog, FileLogConfig } from "./channels/file-log.mjs";
|
|
5
5
|
import { JSONFileLog } from "./channels/json-file-log.mjs";
|
|
6
6
|
import { SentryBreadcrumb, SentryForwarder, SentryInitOptions, SentryLog, SentryLogConfig, SentryScopeLike } from "./channels/sentry-log.mjs";
|
|
7
|
-
import { Logger, log } from "./logger.mjs";
|
|
7
|
+
import { DEFAULT_FLUSH_TIMEOUT_MS, Logger, log } from "./logger.mjs";
|
|
8
8
|
import { DEFAULT_REDACT_KEYS, DEFAULT_REDACT_KEY_SET, normalizeRedactKey } from "./redact/default-keys.mjs";
|
|
9
9
|
import { applyRedact, mergeRedact, resolveRedactKeys } from "./redact/redact.mjs";
|
|
10
|
+
import { MASK_EMAILS_MAX_LENGTH, maskEmail, maskEmailsInText } from "./redact/mask-email.mjs";
|
|
10
11
|
import { CaptureUnhandledOptions, captureAnyUnhandledRejection } from "./utils/capture-unhandled-errors.mjs";
|
|
11
12
|
import { clearMessage } from "./utils/clear-message.mjs";
|
|
12
13
|
import { safeJsonStringify } from "./utils/safe-json-stringify.mjs";
|
|
13
|
-
export { AutoFlushEvent, BasicLogConfigurations, CaptureUnhandledOptions, ConsoleLog, ConsoleLogConfig, DEFAULT_REDACT_KEYS, DEFAULT_REDACT_KEY_SET, DebugMode, FileLog, FileLogConfig, JSONFileLog, LogChannel, LogContract, LogLevel, LogMessage, Logger, LoggingData, OmittedLoggingData, RedactCensor, RedactConfig, SentryBreadcrumb, SentryForwarder, SentryInitOptions, SentryLog, SentryLogConfig, SentryScopeLike, applyRedact, captureAnyUnhandledRejection, clearMessage, log, mergeRedact, normalizeRedactKey, resolveRedactKeys, safeJsonStringify };
|
|
14
|
+
export { AutoFlushEvent, BasicLogConfigurations, CaptureUnhandledOptions, ChannelErrorHandler, ConsoleLog, ConsoleLogConfig, DEFAULT_FLUSH_TIMEOUT_MS, DEFAULT_REDACT_KEYS, DEFAULT_REDACT_KEY_SET, DebugMode, FileLog, FileLogConfig, JSONFileLog, LogChannel, LogContract, LogLevel, LogMessage, Logger, LoggingData, MASK_EMAILS_MAX_LENGTH, OmittedLoggingData, RedactCensor, RedactConfig, SentryBreadcrumb, SentryForwarder, SentryInitOptions, SentryLog, SentryLogConfig, SentryScopeLike, applyRedact, captureAnyUnhandledRejection, clearMessage, log, maskEmail, maskEmailsInText, mergeRedact, normalizeRedactKey, resolveRedactKeys, safeJsonStringify };
|
package/esm/index.mjs
CHANGED
|
@@ -7,10 +7,11 @@ import { SentryLog } from "./channels/sentry-log.mjs";
|
|
|
7
7
|
import "./channels/index.mjs";
|
|
8
8
|
import { DEFAULT_REDACT_KEYS, DEFAULT_REDACT_KEY_SET, normalizeRedactKey } from "./redact/default-keys.mjs";
|
|
9
9
|
import { applyRedact, mergeRedact, resolveRedactKeys } from "./redact/redact.mjs";
|
|
10
|
+
import { MASK_EMAILS_MAX_LENGTH, maskEmail, maskEmailsInText } from "./redact/mask-email.mjs";
|
|
10
11
|
import "./redact/index.mjs";
|
|
11
12
|
import { clearMessage } from "./utils/clear-message.mjs";
|
|
12
|
-
import { Logger, log } from "./logger.mjs";
|
|
13
|
+
import { DEFAULT_FLUSH_TIMEOUT_MS, Logger, log } from "./logger.mjs";
|
|
13
14
|
import { captureAnyUnhandledRejection } from "./utils/capture-unhandled-errors.mjs";
|
|
14
15
|
import "./utils/index.mjs";
|
|
15
16
|
|
|
16
|
-
export { ConsoleLog, DEFAULT_REDACT_KEYS, DEFAULT_REDACT_KEY_SET, FileLog, JSONFileLog, LogChannel, Logger, SentryLog, applyRedact, captureAnyUnhandledRejection, clearMessage, log, mergeRedact, normalizeRedactKey, resolveRedactKeys, safeJsonStringify };
|
|
17
|
+
export { ConsoleLog, DEFAULT_FLUSH_TIMEOUT_MS, DEFAULT_REDACT_KEYS, DEFAULT_REDACT_KEY_SET, FileLog, JSONFileLog, LogChannel, Logger, MASK_EMAILS_MAX_LENGTH, SentryLog, applyRedact, captureAnyUnhandledRejection, clearMessage, log, maskEmail, maskEmailsInText, mergeRedact, normalizeRedactKey, resolveRedactKeys, safeJsonStringify };
|
package/esm/log-channel.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { BasicLogConfigurations, LogContract, LoggingData, RedactConfig } from "./types.mjs";
|
|
2
2
|
|
|
3
|
-
//#region
|
|
3
|
+
//#region ../../packages/logger/src/log-channel.d.ts
|
|
4
4
|
declare abstract class LogChannel<Options extends BasicLogConfigurations = BasicLogConfigurations> implements LogContract {
|
|
5
5
|
/**
|
|
6
6
|
* Channel name
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"log-channel.d.mts","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"log-channel.d.mts","names":[],"sources":["../../../../../../../packages/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":["../../../../../../../packages/logger/src/log-channel.ts"],"sourcesContent":["import type {\n BasicLogConfigurations,\n LogContract,\n LoggingData,\n RedactConfig,\n} from \"./types\";\n\nexport abstract class LogChannel<\n Options extends BasicLogConfigurations = BasicLogConfigurations,\n> implements LogContract {\n /**\n * Channel name\n */\n public name!: string;\n\n /**\n * Channel description\n */\n public description?: string;\n\n /**\n * Determine if channel is logging in terminal\n */\n public terminal = false;\n\n /**\n * Default Configurations\n */\n protected defaultConfigurations: Options = {} as Options;\n\n /**\n * Channel configurations\n */\n protected channelConfigurations: Options = {} as Options; //\n\n /**\n * Determine whether the channel is fully initialized\n */\n protected isInitialized = false;\n\n /**\n * Constructor\n */\n public constructor(configurations?: Options) {\n if (configurations) {\n this.setConfigurations(configurations);\n }\n\n setTimeout(async () => {\n if (this.init) {\n await this.init();\n }\n\n this.isInitialized = true;\n }, 0);\n }\n\n /**\n * Initialize the channel\n */\n protected init?(): void | Promise<void>;\n\n /**\n * Get config value\n */\n protected config<K extends keyof Options>(key: K): Options[K] {\n return (\n this.channelConfigurations[key] ?? (this.defaultConfigurations ?? {})[key]\n );\n }\n\n /**\n * Set configurations\n */\n protected setConfigurations(configurations: Options) {\n this.channelConfigurations = {\n ...this.channelConfigurations,\n ...configurations,\n };\n\n return this;\n }\n\n /**\n * Determine if the message should be logged\n */\n protected shouldBeLogged(data: LoggingData): boolean {\n // check for debug mode\n const allowedLevels = this.config(\"levels\");\n\n if (allowedLevels?.length && !allowedLevels.includes(data.type))\n return false;\n\n const filter = this.config(\"filter\");\n\n if (filter) {\n return filter(data);\n }\n\n return true;\n }\n\n /**\n * Log the given message\n */\n public abstract log(data: LoggingData): void | Promise<void>;\n\n /**\n * Synchronously flush messages\n */\n public flushSync?(): void;\n\n /**\n * Asynchronously flush buffered messages.\n *\n * Optional — channels that write synchronously per entry (e.g. `ConsoleLog`)\n * don't implement it. Buffering channels override this to drain their buffer\n * over async I/O so callers can `await log.flush()` on graceful shutdown.\n */\n public flush?(): void | Promise<void>;\n\n /**\n * Read the channel's redact config (if any). Used by `Logger` to apply\n * per-channel additive redaction on top of the logger-wide floor.\n * Subclasses normally don't override this — set `redact` in your channel\n * configuration instead.\n */\n public getRedactConfig(): RedactConfig | undefined {\n return this.config(\"redact\" as keyof Options) as RedactConfig | undefined;\n }\n\n /**\n * Get date and time formats\n */\n protected getDateAndTimeFormat() {\n const dateFormat = this.config(\"dateFormat\");\n const date = dateFormat?.date ?? \"DD-MM-YYYY\";\n const time = dateFormat?.time ?? \"HH:mm:ss\";\n\n return { date, time };\n }\n\n /**\n * get basic configurations with the given ones\n */\n protected withBasicConfigurations(configurations: Partial<Options>): Options {\n return {\n filter: () => true,\n ...configurations,\n } as any as Options;\n }\n}\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
|
-
import { AutoFlushEvent, BasicLogConfigurations, LogLevel, LoggingData, OmittedLoggingData, RedactConfig } from "./types.mjs";
|
|
1
|
+
import { AutoFlushEvent, BasicLogConfigurations, ChannelErrorHandler, LogLevel, LoggingData, OmittedLoggingData, RedactConfig } from "./types.mjs";
|
|
2
2
|
import { LogChannel } from "./log-channel.mjs";
|
|
3
3
|
|
|
4
|
-
//#region
|
|
4
|
+
//#region ../../packages/logger/src/logger.d.ts
|
|
5
5
|
declare class Logger {
|
|
6
6
|
/**
|
|
7
7
|
* Current channel
|
|
@@ -28,6 +28,18 @@ declare class Logger {
|
|
|
28
28
|
* set here.
|
|
29
29
|
*/
|
|
30
30
|
private redactConfig?;
|
|
31
|
+
/**
|
|
32
|
+
* Deliveries still in flight on async channels, per channel. `log()` never
|
|
33
|
+
* awaits them; `flush()` does, so a graceful shutdown still waits for every
|
|
34
|
+
* entry. Kept per channel so one hung channel cannot hold up another's
|
|
35
|
+
* drain.
|
|
36
|
+
*/
|
|
37
|
+
private pendingDeliveries;
|
|
38
|
+
/**
|
|
39
|
+
* Receives a channel's delivery failure (a sync throw or a rejected async
|
|
40
|
+
* `log()`). Defaults to a single stderr line, never back through the logger.
|
|
41
|
+
*/
|
|
42
|
+
private channelErrorHandler;
|
|
31
43
|
/**
|
|
32
44
|
* Add a new channel
|
|
33
45
|
*/
|
|
@@ -40,7 +52,19 @@ declare class Logger {
|
|
|
40
52
|
autoFlushOn?: AutoFlushEvent[];
|
|
41
53
|
minLevel?: LogLevel;
|
|
42
54
|
redact?: RedactConfig;
|
|
55
|
+
onChannelError?: ChannelErrorHandler;
|
|
43
56
|
}): this;
|
|
57
|
+
/**
|
|
58
|
+
* Handle a channel's delivery failure. Logging is fire-and-forget, so a
|
|
59
|
+
* channel that throws or rejects never reaches the call site and never
|
|
60
|
+
* becomes an unhandled rejection; it goes to this handler instead. The
|
|
61
|
+
* default writes one line to stderr. The handler must not log through this
|
|
62
|
+
* logger (a failing channel would loop).
|
|
63
|
+
*
|
|
64
|
+
* @example
|
|
65
|
+
* log.onChannelError((error, channel) => metrics.increment(`log.${channel.name}.failed`));
|
|
66
|
+
*/
|
|
67
|
+
onChannelError(handler: ChannelErrorHandler): this;
|
|
44
68
|
/**
|
|
45
69
|
* Set the logger-wide redaction floor. Applied to every entry before
|
|
46
70
|
* fan-out; channel configs add more paths on top, never fewer. Pass
|
|
@@ -88,28 +112,40 @@ declare class Logger {
|
|
|
88
112
|
* — each channel sees its own shallow clone so one channel cannot observe
|
|
89
113
|
* another's mutations (e.g. a later terminal channel still sees the original
|
|
90
114
|
* colored message).
|
|
115
|
+
*
|
|
116
|
+
* Synchronous and fire-and-forget: it returns the logger, not a promise.
|
|
117
|
+
* Async channel deliveries are tracked and awaited by {@link flush}; a
|
|
118
|
+
* channel that throws or rejects is isolated from the others and reported
|
|
119
|
+
* to {@link onChannelError}.
|
|
120
|
+
*/
|
|
121
|
+
log(data: LoggingData): this;
|
|
122
|
+
/**
|
|
123
|
+
* Prepare and hand one entry to one channel, isolating its failure (a
|
|
124
|
+
* channel redaction that throws included) and tracking an async delivery
|
|
125
|
+
* until it settles.
|
|
91
126
|
*/
|
|
92
|
-
|
|
127
|
+
private deliver;
|
|
128
|
+
private reportChannelError;
|
|
93
129
|
/**
|
|
94
130
|
* Make debug log
|
|
95
131
|
*/
|
|
96
|
-
debug(dataOrModule: OmittedLoggingData | string, action?: string, message?: any, context?: Record<string, any>):
|
|
132
|
+
debug(dataOrModule: OmittedLoggingData | string, action?: string, message?: any, context?: Record<string, any>): this;
|
|
97
133
|
/**
|
|
98
134
|
* Make info log
|
|
99
135
|
*/
|
|
100
|
-
info(dataOrModule: OmittedLoggingData | string, action?: string, message?: any, context?: Record<string, any>):
|
|
136
|
+
info(dataOrModule: OmittedLoggingData | string, action?: string, message?: any, context?: Record<string, any>): this;
|
|
101
137
|
/**
|
|
102
138
|
* Make warn log
|
|
103
139
|
*/
|
|
104
|
-
warn(dataOrModule: OmittedLoggingData | string, action?: string, message?: any, context?: Record<string, any>):
|
|
140
|
+
warn(dataOrModule: OmittedLoggingData | string, action?: string, message?: any, context?: Record<string, any>): this;
|
|
105
141
|
/**
|
|
106
142
|
* Make error log
|
|
107
143
|
*/
|
|
108
|
-
error(dataOrModule: OmittedLoggingData | string, action?: string, message?: any, context?: Record<string, any>):
|
|
144
|
+
error(dataOrModule: OmittedLoggingData | string, action?: string, message?: any, context?: Record<string, any>): this;
|
|
109
145
|
/**
|
|
110
146
|
* Make success log
|
|
111
147
|
*/
|
|
112
|
-
success(dataOrModule: OmittedLoggingData | string, action?: string, message?: any, context?: Record<string, any>):
|
|
148
|
+
success(dataOrModule: OmittedLoggingData | string, action?: string, message?: any, context?: Record<string, any>): this;
|
|
113
149
|
/**
|
|
114
150
|
* Make fatal log — for unrecoverable failures where the application is going
|
|
115
151
|
* down (failed bootstrap, lost connection to a required dependency that the
|
|
@@ -119,7 +155,7 @@ declare class Logger {
|
|
|
119
155
|
* `fatal` does NOT auto-flush or exit. The caller decides whether to call
|
|
120
156
|
* `await log.flush()` and `process.exit(...)`.
|
|
121
157
|
*/
|
|
122
|
-
fatal(dataOrModule: OmittedLoggingData | string, action?: string, message?: any, context?: Record<string, any>):
|
|
158
|
+
fatal(dataOrModule: OmittedLoggingData | string, action?: string, message?: any, context?: Record<string, any>): this;
|
|
123
159
|
/**
|
|
124
160
|
* Log an `error` entry when `condition` is falsy. No-op otherwise — the
|
|
125
161
|
* entry is never built and channels are not invoked, so this is genuinely
|
|
@@ -129,7 +165,7 @@ declare class Logger {
|
|
|
129
165
|
* @example
|
|
130
166
|
* log.assert(user !== null, "auth", "session", "user vanished mid-flight", { sessionId });
|
|
131
167
|
*/
|
|
132
|
-
assert(condition: unknown, module: string, action: string, message: any, context?: Record<string, any>):
|
|
168
|
+
assert(condition: unknown, module: string, action: string, message: any, context?: Record<string, any>): this;
|
|
133
169
|
/**
|
|
134
170
|
* Start a duration timer. The returned function emits an `info` entry
|
|
135
171
|
* with `completed in <ms>ms` and a `durationMs` field in `context` when
|
|
@@ -140,7 +176,7 @@ declare class Logger {
|
|
|
140
176
|
* const user = await usersRepo.findById(id);
|
|
141
177
|
* end({ id, found: !!user });
|
|
142
178
|
*/
|
|
143
|
-
timer(module: string, action: string): (extra?: Record<string, any>) =>
|
|
179
|
+
timer(module: string, action: string): (extra?: Record<string, any>) => this;
|
|
144
180
|
/**
|
|
145
181
|
* Get channel by name
|
|
146
182
|
*/
|
|
@@ -150,7 +186,9 @@ declare class Logger {
|
|
|
150
186
|
*/
|
|
151
187
|
flushSync(): void;
|
|
152
188
|
/**
|
|
153
|
-
*
|
|
189
|
+
* Wait for every in-flight async delivery, then drain every channel that
|
|
190
|
+
* implements `flush()` — bounded by `timeout` (default
|
|
191
|
+
* {@link DEFAULT_FLUSH_TIMEOUT_MS}).
|
|
154
192
|
*
|
|
155
193
|
* Unlike {@link flushSync}, this awaits each channel's async I/O — the
|
|
156
194
|
* correct call for a graceful shutdown that can afford to wait
|
|
@@ -158,18 +196,30 @@ declare class Logger {
|
|
|
158
196
|
* `process.exit`). A channel whose delivery is async (a network transport,
|
|
159
197
|
* an async disk write) implements `flush()`, not `flushSync()`.
|
|
160
198
|
*
|
|
161
|
-
* Channels
|
|
162
|
-
*
|
|
163
|
-
*
|
|
199
|
+
* Channels drain concurrently and independently: each waits for its own
|
|
200
|
+
* pending deliveries (including ones logged while the flush runs), then
|
|
201
|
+
* runs its `flush()`. A channel whose delivery hangs therefore cannot hold
|
|
202
|
+
* up another channel's drain, and a channel whose flush rejects can neither
|
|
203
|
+
* stop the others nor escape as an unhandled rejection. When `timeout`
|
|
204
|
+
* elapses, `flush()` resolves anyway and each channel still draining is
|
|
205
|
+
* reported to {@link onChannelError}. Channels without `flush()` only wait
|
|
206
|
+
* for their deliveries.
|
|
164
207
|
*
|
|
165
208
|
* @example
|
|
166
209
|
* async function shutdown() {
|
|
167
210
|
* await httpServer.close();
|
|
168
|
-
* await log.flush();
|
|
211
|
+
* await log.flush({ timeout: 3000 });
|
|
169
212
|
* process.exit(0);
|
|
170
213
|
* }
|
|
171
214
|
*/
|
|
172
|
-
flush(
|
|
215
|
+
flush(options?: {
|
|
216
|
+
timeout?: number;
|
|
217
|
+
}): Promise<void>;
|
|
218
|
+
/**
|
|
219
|
+
* Wait until the channel has no delivery in flight, run its `flush()`, and
|
|
220
|
+
* repeat while that flush let new deliveries in.
|
|
221
|
+
*/
|
|
222
|
+
private drainChannel;
|
|
173
223
|
/**
|
|
174
224
|
* Register one process-level handler per event that calls `flushSync()`
|
|
175
225
|
* before the process terminates.
|
|
@@ -195,6 +245,11 @@ declare class Logger {
|
|
|
195
245
|
*/
|
|
196
246
|
disableAutoFlush(): this;
|
|
197
247
|
}
|
|
248
|
+
/**
|
|
249
|
+
* Default `timeout` of {@link Logger.flush}: long enough for a healthy network
|
|
250
|
+
* channel, short enough that a hung one cannot eat a shutdown budget.
|
|
251
|
+
*/
|
|
252
|
+
declare const DEFAULT_FLUSH_TIMEOUT_MS = 5000;
|
|
198
253
|
/**
|
|
199
254
|
* The package singleton. Use this for everyday logging — `log.info(...)`,
|
|
200
255
|
* `log.error(...)`, `log.configure(...)`. Custom logger instances can be
|
|
@@ -211,5 +266,5 @@ declare class Logger {
|
|
|
211
266
|
*/
|
|
212
267
|
declare const log: Logger;
|
|
213
268
|
//#endregion
|
|
214
|
-
export { Logger, log };
|
|
269
|
+
export { DEFAULT_FLUSH_TIMEOUT_MS, Logger, log };
|
|
215
270
|
//# sourceMappingURL=logger.d.mts.map
|