@warlock.js/logger 4.1.15 → 4.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -0
- package/LICENSE +21 -0
- package/README.md +146 -145
- package/cjs/index.cjs +276 -11
- package/cjs/index.cjs.map +1 -1
- package/esm/channels/console-log.d.mts +1 -1
- package/esm/channels/console-log.d.mts.map +1 -1
- package/esm/channels/console-log.mjs +4 -1
- package/esm/channels/console-log.mjs.map +1 -1
- package/esm/channels/file-log.d.mts +13 -3
- package/esm/channels/file-log.d.mts.map +1 -1
- package/esm/channels/file-log.mjs +15 -1
- package/esm/channels/file-log.mjs.map +1 -1
- package/esm/channels/index.mjs +1 -0
- package/esm/channels/json-file-log.d.mts +1 -1
- package/esm/channels/json-file-log.d.mts.map +1 -1
- package/esm/channels/json-file-log.mjs +1 -1
- package/esm/channels/json-file-log.mjs.map +1 -1
- package/esm/channels/sentry-log.d.mts +182 -0
- package/esm/channels/sentry-log.d.mts.map +1 -0
- package/esm/channels/sentry-log.mjs +202 -0
- package/esm/channels/sentry-log.mjs.map +1 -0
- package/esm/index.d.mts +2 -1
- package/esm/index.mjs +2 -1
- package/esm/log-channel.d.mts +9 -1
- package/esm/log-channel.d.mts.map +1 -1
- package/esm/log-channel.mjs +1 -1
- package/esm/log-channel.mjs.map +1 -1
- package/esm/logger.d.mts +32 -1
- package/esm/logger.d.mts.map +1 -1
- package/esm/logger.mjs +44 -2
- package/esm/logger.mjs.map +1 -1
- package/esm/redact/redact.d.mts +1 -1
- package/esm/redact/redact.d.mts.map +1 -1
- package/esm/redact/redact.mjs +1 -1
- package/esm/redact/redact.mjs.map +1 -1
- package/esm/types.d.mts +19 -3
- package/esm/types.d.mts.map +1 -1
- package/esm/utils/capture-unhandled-errors.d.mts +9 -1
- package/esm/utils/capture-unhandled-errors.d.mts.map +1 -1
- package/esm/utils/capture-unhandled-errors.mjs +10 -2
- package/esm/utils/capture-unhandled-errors.mjs.map +1 -1
- package/esm/utils/clear-message.d.mts +1 -1
- package/esm/utils/clear-message.d.mts.map +1 -1
- package/esm/utils/clear-message.mjs +1 -1
- package/esm/utils/clear-message.mjs.map +1 -1
- package/esm/utils/safe-json-stringify.d.mts +1 -1
- package/esm/utils/safe-json-stringify.d.mts.map +1 -1
- package/esm/utils/safe-json-stringify.mjs +1 -1
- package/esm/utils/safe-json-stringify.mjs.map +1 -1
- package/llms-full.txt +1497 -1296
- package/llms.txt +20 -19
- package/package.json +5 -2
- package/skills/capture-unhandled-errors/SKILL.md +103 -103
- package/skills/filter-log-entries/SKILL.md +120 -120
- package/skills/flush-logs-on-shutdown/SKILL.md +117 -91
- package/skills/logger-basics/SKILL.md +88 -85
- package/skills/overview/SKILL.md +90 -86
- package/skills/pick-log-channel/SKILL.md +155 -139
- package/skills/ship-logs-to-sentry/SKILL.md +118 -0
- package/skills/write-custom-log-channel/SKILL.md +190 -160
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-log.mjs","names":[],"sources":["../../../../../../@warlock.js/logger/src/channels/file-log.ts"],"sourcesContent":["import { ensureDirectoryAsync } from \"@warlock.js/fs\";\r\nimport dayjs from \"dayjs\";\r\nimport fs from \"fs\";\r\nimport { EOL } from \"os\";\r\nimport path from \"path\";\r\nimport { LogChannel } from \"../log-channel\";\r\nimport type {\r\n BasicLogConfigurations,\r\n LogContract,\r\n LoggingData,\r\n LogLevel,\r\n LogMessage,\r\n} from \"../types\";\r\n\r\n// TODO: Add max messages per file before rotation\r\n\r\nexport type FileLogConfig = BasicLogConfigurations & {\r\n storagePath?: string;\r\n /**\r\n * File name, without extension\r\n */\r\n name?: string;\r\n /**\r\n * chunk mode\r\n * If set to `single`, the logs will be created in a single file, unless the rotate is set to true\r\n * If set to `daily`, the logs will be created in a daily file, unless the rotate is set to true\r\n * If set to `hourly`, the logs will be created in an hourly file, unless the rotate is set to true\r\n * @default single\r\n */\r\n chunk?: \"single\" | \"daily\" | \"hourly\";\r\n /**\r\n * Whether to rotate the file\r\n *\r\n * @default true\r\n */\r\n rotate?: boolean;\r\n /**\r\n * File Extension\r\n *\r\n * @default log\r\n */\r\n extension?: string;\r\n /**\r\n * If rotate is set, the rotate name will be added to the file name suffixed with `-`\r\n *\r\n * @default DD-MM-YYYY\r\n */\r\n rotateFileName?: string;\r\n /**\r\n * Max file size before rotating the file\r\n *\r\n * @default 10MB\r\n */\r\n maxFileSize?: number;\r\n /**\r\n * Set the max messages that needs to be added before writing to the file\r\n *\r\n * @default 100\r\n */\r\n maxMessagesToWrite?: number;\r\n /**\r\n * Group logs by\r\n * Please note that the order matters here\r\n * For example, if you set `groupBy: ['level', 'module']`, the logs will be added in level name first, then by module\r\n *\r\n * @default none\r\n */\r\n groupBy?: (\"level\" | \"module\" | \"action\")[];\r\n /**\r\n * Define what levels should be logged\r\n *\r\n * @default all\r\n */\r\n levels?: LogLevel[];\r\n /**\r\n * Date and time format\r\n */\r\n dateFormat?: {\r\n date?: string;\r\n time?: string;\r\n };\r\n};\r\n\r\nexport class FileLog extends LogChannel<FileLogConfig> implements LogContract {\r\n /**\r\n * {@inheritdoc}\r\n */\r\n public name = \"file\";\r\n\r\n /**\r\n * Messages buffer\r\n */\r\n protected messages: LogMessage[] = [];\r\n\r\n /**\r\n * Grouped messages\r\n */\r\n protected groupedMessages: Record<string, LogMessage[]> = {};\r\n\r\n /**\r\n * Default channel configurations\r\n */\r\n protected defaultConfigurations: FileLogConfig = {\r\n storagePath: process.cwd() + \"/storage/logs\",\r\n rotate: true,\r\n name: \"app\",\r\n extension: \"log\",\r\n chunk: \"single\",\r\n maxMessagesToWrite: 100,\r\n filter: () => true,\r\n maxFileSize: 10 * 1024 * 1024, // 10MB\r\n get rotateFileName() {\r\n return dayjs().format(\"DD-MM-YYYY\");\r\n },\r\n dateFormat: {\r\n date: \"DD-MM-YYYY\",\r\n time: \"HH:mm:ss\",\r\n },\r\n };\r\n\r\n /**\r\n * Last write time\r\n */\r\n protected lastWriteTime = Date.now();\r\n\r\n /**\r\n * A flag to determine if the file is being written\r\n */\r\n protected isWriting = false;\r\n\r\n /**\r\n * Handle for the periodic flush interval. Stored so it can be cleared\r\n * in `dispose()` — long-lived processes that create channels dynamically\r\n * would otherwise leak one timer per channel.\r\n */\r\n protected flushIntervalHandle?: NodeJS.Timeout;\r\n\r\n /**\r\n * Check file size for file rotation\r\n */\r\n protected async checkAndRotateFile(filePath = this.filePath) {\r\n if (!this.config(\"rotate\")) return;\r\n\r\n try {\r\n const stats = await fs.promises.stat(filePath);\r\n if (stats.size >= this.config(\"maxFileSize\")!) {\r\n await this.rotateLogFile();\r\n }\r\n } catch (error: any) {\r\n // ENOENT is expected when the file hasn't been created yet — there is\r\n // nothing to rotate, so stay silent. Surface anything else.\r\n if (error.code !== \"ENOENT\") {\r\n console.error(\"Error checking log file:\", error);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Rotate log file\r\n */\r\n protected async rotateLogFile() {\r\n const fileName = `${this.fileName}-${this.config(\"rotateFileName\")}-${Date.now()}`;\r\n\r\n const extension = this.extension;\r\n\r\n const rotatedFilePath = path.join(this.storagePath, `${fileName}.${extension}`);\r\n\r\n await fs.promises.rename(this.filePath, rotatedFilePath).catch((error) => {\r\n console.error(\"Error rotating file:\", error);\r\n });\r\n }\r\n\r\n /**\r\n * Flush messages\r\n *\r\n * Starts a periodic re-check so low-traffic channels don't sit on buffered\r\n * entries indefinitely. The handle is stored on the instance so `dispose()`\r\n * can stop it — without this, every channel leaks a timer for the lifetime\r\n * of the process.\r\n */\r\n protected initMessageFlush() {\r\n this.flushIntervalHandle = setInterval(() => {\r\n if (\r\n this.messages.length > 0 &&\r\n (this.messages.length >= this.maxMessagesToWrite || Date.now() - this.lastWriteTime > 5000)\r\n ) {\r\n this.writeMessagesToFile();\r\n }\r\n }, 5000);\r\n }\r\n\r\n /**\r\n * Stop the background flush interval and drain any buffered entries.\r\n *\r\n * Call this when discarding a channel (e.g. reconfiguring the logger at\r\n * runtime) so the 5-second timer doesn't keep the event loop alive. Safe to\r\n * call more than once.\r\n */\r\n public dispose(): void {\r\n if (this.flushIntervalHandle) {\r\n clearInterval(this.flushIntervalHandle);\r\n this.flushIntervalHandle = undefined;\r\n }\r\n\r\n this.flushSync();\r\n }\r\n\r\n /**\r\n * Get file path\r\n */\r\n public get filePath() {\r\n const fileName = this.fileName;\r\n\r\n const extension = this.extension;\r\n\r\n return path.join(this.storagePath, `${fileName}.${extension}`);\r\n }\r\n\r\n /**\r\n * Get max messages\r\n */\r\n protected get maxMessagesToWrite(): number {\r\n return this.config(\"maxMessagesToWrite\")!;\r\n }\r\n\r\n /**\r\n * Get file name\r\n */\r\n public get fileName(): string {\r\n const debugLevel = this.config(\"chunk\")!;\r\n\r\n switch (debugLevel) {\r\n case \"single\":\r\n default:\r\n return this.config(\"name\")!;\r\n case \"daily\":\r\n return dayjs().format(\"DD-MM-YYYY\");\r\n case \"hourly\":\r\n return dayjs().format(\"DD-MM-YYYY-HH-00-00-a\");\r\n }\r\n }\r\n\r\n /**\r\n * Get file extension\r\n */\r\n public get extension(): string {\r\n return this.config(\"extension\")!;\r\n }\r\n\r\n /**\r\n * Get content\r\n */\r\n protected get content() {\r\n return this.messages.map((message) => message.content).join(EOL) + EOL;\r\n }\r\n\r\n /**\r\n * Get storage path\r\n */\r\n public get storagePath(): string {\r\n return this.config(\"storagePath\")!;\r\n }\r\n\r\n /**\r\n * {@inheritdoc}\r\n */\r\n protected async init() {\r\n const logsDirectory = this.storagePath;\r\n\r\n await ensureDirectoryAsync(logsDirectory);\r\n\r\n this.initMessageFlush();\r\n }\r\n\r\n /**\r\n * Synchronously flush messages\r\n */\r\n public flushSync(): void {\r\n if (this.messages.length === 0 && Object.keys(this.groupedMessages).length === 0) return;\r\n\r\n if (this.messagedShouldBeGrouped) {\r\n this.prepareGroupedMessages();\r\n for (const key in this.groupedMessages) {\r\n const directoryPath = path.join(this.storagePath, key);\r\n fs.mkdirSync(directoryPath, { recursive: true });\r\n const filePath = path.join(directoryPath, `${this.fileName}.${this.extension}`);\r\n const content = this.groupedMessages[key].map((message) => message.content).join(EOL) + EOL;\r\n fs.appendFileSync(filePath, content);\r\n }\r\n } else {\r\n fs.mkdirSync(this.storagePath, { recursive: true });\r\n fs.appendFileSync(this.filePath, this.content);\r\n }\r\n\r\n this.onSave();\r\n }\r\n\r\n /**\r\n * {@inheritdoc}\r\n */\r\n public async log(data: LoggingData) {\r\n const { module, action, message, type: level, context } = data;\r\n\r\n if (!this.shouldBeLogged(data)) return;\r\n\r\n const { date: dateFormat, time } = this.getDateAndTimeFormat();\r\n\r\n const date = dayjs().format(dateFormat + \" \" + time);\r\n\r\n let content = `[${date}] [${level}] [${module}][${action}]: `;\r\n\r\n let stack: string | undefined;\r\n\r\n // check if message is an instance of Error\r\n if (message instanceof Error) {\r\n // in that case we need to store the error message and stack trace\r\n content += message.message + EOL;\r\n content += `[trace]` + EOL;\r\n content += message.stack;\r\n stack = message.stack;\r\n } else {\r\n content += message;\r\n }\r\n\r\n this.messages.push({\r\n content,\r\n level,\r\n date,\r\n module,\r\n action,\r\n stack,\r\n context,\r\n timestamp: new Date().toISOString(),\r\n });\r\n\r\n await this.checkIfMessagesShouldBeWritten(); // Immediate check on buffer size\r\n }\r\n\r\n /**\r\n * Check if messages should be written\r\n */\r\n protected async checkIfMessagesShouldBeWritten() {\r\n if (this.messages.length >= this.maxMessagesToWrite || Date.now() - this.lastWriteTime > 5000) {\r\n await this.writeMessagesToFile();\r\n }\r\n }\r\n\r\n /**\r\n * Should be called after messages are saved\r\n */\r\n protected onSave() {\r\n this.messages = [];\r\n this.groupedMessages = {};\r\n this.isWriting = false;\r\n this.lastWriteTime = Date.now();\r\n }\r\n\r\n /**\r\n * Check if messages should be grouped\r\n */\r\n protected get messagedShouldBeGrouped(): boolean {\r\n return Number(this.config(\"groupBy\")?.length) > 0;\r\n }\r\n\r\n /**\r\n * Write messages to the file\r\n */\r\n protected async writeMessagesToFile() {\r\n if (this.messages.length === 0 || this.isWriting || !this.isInitialized) return;\r\n\r\n this.isWriting = true;\r\n\r\n if (this.messagedShouldBeGrouped) {\r\n return await this.writeGroupedMessagesToFile();\r\n }\r\n\r\n await this.checkAndRotateFile(); // Ensure we check file size before writing\r\n\r\n try {\r\n await this.write(this.filePath, this.content);\r\n this.onSave();\r\n } catch (error) {\r\n console.error(\"Failed to write log:\", error);\r\n // Implement fallback logic here\r\n this.isWriting = false;\r\n }\r\n }\r\n\r\n /**\r\n * Write grouped messages to the file\r\n */\r\n protected async writeGroupedMessagesToFile(): Promise<void> {\r\n // first step, is to group the messages\r\n this.prepareGroupedMessages();\r\n\r\n // now each key in the grouped messages, represents the directory path that should extend the storage path\r\n for (const key in this.groupedMessages) {\r\n const directoryPath = path.join(this.storagePath, key);\r\n\r\n await ensureDirectoryAsync(directoryPath);\r\n\r\n const filePath = path.join(directoryPath, `${this.fileName}.${this.extension}`);\r\n\r\n await this.checkAndRotateFile(filePath); // Ensure we check file size before writing\r\n\r\n const content = this.groupedMessages[key].map((message) => message.content).join(EOL) + EOL;\r\n\r\n try {\r\n await this.write(filePath, content);\r\n } catch (error) {\r\n console.error(\"Failed to write log:\", error);\r\n }\r\n }\r\n\r\n this.onSave();\r\n this.isWriting = false;\r\n }\r\n\r\n /**\r\n * Prepare grouped messages\r\n */\r\n protected prepareGroupedMessages(): void {\r\n this.messages.forEach((message) => {\r\n const key = this.config(\"groupBy\")!\r\n .map((groupKey) => encodeURIComponent(message[groupKey]))\r\n .join(\"/\");\r\n\r\n this.groupedMessages[key] = this.groupedMessages[key] || [];\r\n this.groupedMessages[key].push(message);\r\n });\r\n }\r\n\r\n /**\r\n * Start writing to the file\r\n */\r\n protected async write(filePath: string, content: string) {\r\n return new Promise((resolve, reject) => {\r\n const writer = fs.createWriteStream(filePath, { flags: \"a\" });\r\n\r\n writer.write(content, (error) => {\r\n writer.end();\r\n if (error) {\r\n reject(error);\r\n } else {\r\n resolve(true);\r\n }\r\n });\r\n });\r\n }\r\n}\r\n"],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ACX,IAAI,OACF,OAAO,KAAK;SAEZ,QAAQ,IAAI;GAEhB,CAAC;EACH,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"file-log.mjs","names":[],"sources":["../../../../../../../@warlock.js/logger/src/channels/file-log.ts"],"sourcesContent":["import { ensureDirectoryAsync } from \"@warlock.js/fs\";\r\nimport dayjs from \"dayjs\";\r\nimport fs from \"fs\";\r\nimport { EOL } from \"os\";\r\nimport path from \"path\";\r\nimport { LogChannel } from \"../log-channel\";\r\nimport type {\r\n BasicLogConfigurations,\r\n LogContract,\r\n LoggingData,\r\n LogLevel,\r\n LogMessage,\r\n} from \"../types\";\r\n\r\n// TODO: Add max messages per file before rotation\r\n\r\nexport type FileLogConfig = BasicLogConfigurations & {\r\n storagePath?: string;\r\n /**\r\n * File name, without extension\r\n */\r\n name?: string;\r\n /**\r\n * chunk mode\r\n * If set to `single`, the logs will be created in a single file, unless the rotate is set to true\r\n * If set to `daily`, the logs will be created in a daily file, unless the rotate is set to true\r\n * If set to `hourly`, the logs will be created in an hourly file, unless the rotate is set to true\r\n * @default single\r\n */\r\n chunk?: \"single\" | \"daily\" | \"hourly\";\r\n /**\r\n * Whether to rotate the file\r\n *\r\n * @default true\r\n */\r\n rotate?: boolean;\r\n /**\r\n * File Extension\r\n *\r\n * @default log\r\n */\r\n extension?: string;\r\n /**\r\n * If rotate is set, the rotate name will be added to the file name suffixed with `-`\r\n *\r\n * @default DD-MM-YYYY\r\n */\r\n rotateFileName?: string;\r\n /**\r\n * Max file size before rotating the file\r\n *\r\n * @default 10MB\r\n */\r\n maxFileSize?: number;\r\n /**\r\n * Set the max messages that needs to be added before writing to the file\r\n *\r\n * @default 100\r\n */\r\n maxMessagesToWrite?: number;\r\n /**\r\n * Group logs by\r\n * Please note that the order matters here\r\n * For example, if you set `groupBy: ['level', 'module']`, the logs will be added in level name first, then by module\r\n *\r\n * @default none\r\n */\r\n groupBy?: (\"level\" | \"module\" | \"action\")[];\r\n /**\r\n * Define what levels should be logged\r\n *\r\n * @default all\r\n */\r\n levels?: LogLevel[];\r\n /**\r\n * Date and time format\r\n */\r\n dateFormat?: {\r\n date?: string;\r\n time?: string;\r\n };\r\n};\r\n\r\nexport class FileLog extends LogChannel<FileLogConfig> implements LogContract {\r\n /**\r\n * {@inheritdoc}\r\n */\r\n public name = \"file\";\r\n\r\n /**\r\n * Messages buffer\r\n */\r\n protected messages: LogMessage[] = [];\r\n\r\n /**\r\n * Grouped messages\r\n */\r\n protected groupedMessages: Record<string, LogMessage[]> = {};\r\n\r\n /**\r\n * Default channel configurations\r\n */\r\n protected defaultConfigurations: FileLogConfig = {\r\n storagePath: process.cwd() + \"/storage/logs\",\r\n rotate: true,\r\n name: \"app\",\r\n extension: \"log\",\r\n chunk: \"single\",\r\n maxMessagesToWrite: 100,\r\n filter: () => true,\r\n maxFileSize: 10 * 1024 * 1024, // 10MB\r\n get rotateFileName() {\r\n return dayjs().format(\"DD-MM-YYYY\");\r\n },\r\n dateFormat: {\r\n date: \"DD-MM-YYYY\",\r\n time: \"HH:mm:ss\",\r\n },\r\n };\r\n\r\n /**\r\n * Last write time\r\n */\r\n protected lastWriteTime = Date.now();\r\n\r\n /**\r\n * A flag to determine if the file is being written\r\n */\r\n protected isWriting = false;\r\n\r\n /**\r\n * Handle for the periodic flush interval. Stored so it can be cleared\r\n * in `dispose()` — long-lived processes that create channels dynamically\r\n * would otherwise leak one timer per channel.\r\n */\r\n protected flushIntervalHandle?: NodeJS.Timeout;\r\n\r\n /**\r\n * Check file size for file rotation\r\n */\r\n protected async checkAndRotateFile(filePath = this.filePath) {\r\n if (!this.config(\"rotate\")) return;\r\n\r\n try {\r\n const stats = await fs.promises.stat(filePath);\r\n if (stats.size >= this.config(\"maxFileSize\")!) {\r\n await this.rotateLogFile();\r\n }\r\n } catch (error: any) {\r\n // ENOENT is expected when the file hasn't been created yet — there is\r\n // nothing to rotate, so stay silent. Surface anything else.\r\n if (error.code !== \"ENOENT\") {\r\n console.error(\"Error checking log file:\", error);\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Rotate log file\r\n */\r\n protected async rotateLogFile() {\r\n const fileName = `${this.fileName}-${this.config(\"rotateFileName\")}-${Date.now()}`;\r\n\r\n const extension = this.extension;\r\n\r\n const rotatedFilePath = path.join(this.storagePath, `${fileName}.${extension}`);\r\n\r\n await fs.promises.rename(this.filePath, rotatedFilePath).catch((error) => {\r\n console.error(\"Error rotating file:\", error);\r\n });\r\n }\r\n\r\n /**\r\n * Flush messages\r\n *\r\n * Starts a periodic re-check so low-traffic channels don't sit on buffered\r\n * entries indefinitely. The handle is stored on the instance so `dispose()`\r\n * can stop it — without this, every channel leaks a timer for the lifetime\r\n * of the process.\r\n */\r\n protected initMessageFlush() {\r\n this.flushIntervalHandle = setInterval(() => {\r\n if (\r\n this.messages.length > 0 &&\r\n (this.messages.length >= this.maxMessagesToWrite || Date.now() - this.lastWriteTime > 5000)\r\n ) {\r\n this.writeMessagesToFile();\r\n }\r\n }, 5000);\r\n }\r\n\r\n /**\r\n * Stop the background flush interval and drain any buffered entries.\r\n *\r\n * Call this when discarding a channel (e.g. reconfiguring the logger at\r\n * runtime) so the 5-second timer doesn't keep the event loop alive. Safe to\r\n * call more than once.\r\n */\r\n public dispose(): void {\r\n if (this.flushIntervalHandle) {\r\n clearInterval(this.flushIntervalHandle);\r\n this.flushIntervalHandle = undefined;\r\n }\r\n\r\n this.flushSync();\r\n }\r\n\r\n /**\r\n * Get file path\r\n */\r\n public get filePath() {\r\n const fileName = this.fileName;\r\n\r\n const extension = this.extension;\r\n\r\n return path.join(this.storagePath, `${fileName}.${extension}`);\r\n }\r\n\r\n /**\r\n * Get max messages\r\n */\r\n protected get maxMessagesToWrite(): number {\r\n return this.config(\"maxMessagesToWrite\")!;\r\n }\r\n\r\n /**\r\n * Get file name\r\n */\r\n public get fileName(): string {\r\n const debugLevel = this.config(\"chunk\")!;\r\n\r\n switch (debugLevel) {\r\n case \"single\":\r\n default:\r\n return this.config(\"name\")!;\r\n case \"daily\":\r\n return dayjs().format(\"DD-MM-YYYY\");\r\n case \"hourly\":\r\n return dayjs().format(\"DD-MM-YYYY-HH-00-00-a\");\r\n }\r\n }\r\n\r\n /**\r\n * Get file extension\r\n */\r\n public get extension(): string {\r\n return this.config(\"extension\")!;\r\n }\r\n\r\n /**\r\n * Get content\r\n */\r\n protected get content() {\r\n return this.messages.map((message) => message.content).join(EOL) + EOL;\r\n }\r\n\r\n /**\r\n * Get storage path\r\n */\r\n public get storagePath(): string {\r\n return this.config(\"storagePath\")!;\r\n }\r\n\r\n /**\r\n * {@inheritdoc}\r\n */\r\n protected async init() {\r\n const logsDirectory = this.storagePath;\r\n\r\n await ensureDirectoryAsync(logsDirectory);\r\n\r\n this.initMessageFlush();\r\n }\r\n\r\n /**\r\n * Synchronously flush messages\r\n */\r\n public flushSync(): void {\r\n if (this.messages.length === 0 && Object.keys(this.groupedMessages).length === 0) return;\r\n\r\n if (this.messagedShouldBeGrouped) {\r\n this.prepareGroupedMessages();\r\n for (const key in this.groupedMessages) {\r\n const directoryPath = path.join(this.storagePath, key);\r\n fs.mkdirSync(directoryPath, { recursive: true });\r\n const filePath = path.join(directoryPath, `${this.fileName}.${this.extension}`);\r\n const content = this.groupedMessages[key].map((message) => message.content).join(EOL) + EOL;\r\n fs.appendFileSync(filePath, content);\r\n }\r\n } else {\r\n fs.mkdirSync(this.storagePath, { recursive: true });\r\n fs.appendFileSync(this.filePath, this.content);\r\n }\r\n\r\n this.onSave();\r\n }\r\n\r\n /**\r\n * Asynchronously drain buffered entries to disk.\r\n *\r\n * The async analogue of {@link flushSync}: it reuses the same async writer\r\n * as the background interval, so a caller on a graceful-shutdown path can\r\n * `await channel.flush()` (or `await log.flush()`) and rely on the buffer\r\n * being on disk once it resolves. `JSONFileLog` inherits this unchanged —\r\n * its overridden `writeMessagesToFile` performs the JSON merge.\r\n */\r\n public async flush(): Promise<void> {\r\n if (this.messages.length === 0 && Object.keys(this.groupedMessages).length === 0) {\r\n return;\r\n }\r\n\r\n // Clear the in-flight lock so a deliberate drain is never short-circuited\r\n // by a half-finished background write, then await the async writer to\r\n // completion — unlike the fire-and-forget interval, callers depend on the\r\n // buffer reaching disk before this resolves.\r\n this.isWriting = false;\r\n\r\n await this.writeMessagesToFile();\r\n }\r\n\r\n /**\r\n * {@inheritdoc}\r\n */\r\n public async log(data: LoggingData) {\r\n const { module, action, message, type: level, context } = data;\r\n\r\n if (!this.shouldBeLogged(data)) return;\r\n\r\n const { date: dateFormat, time } = this.getDateAndTimeFormat();\r\n\r\n const date = dayjs().format(dateFormat + \" \" + time);\r\n\r\n let content = `[${date}] [${level}] [${module}][${action}]: `;\r\n\r\n let stack: string | undefined;\r\n\r\n // check if message is an instance of Error\r\n if (message instanceof Error) {\r\n // in that case we need to store the error message and stack trace\r\n content += message.message + EOL;\r\n content += `[trace]` + EOL;\r\n content += message.stack;\r\n stack = message.stack;\r\n } else {\r\n content += message;\r\n }\r\n\r\n this.messages.push({\r\n content,\r\n level,\r\n date,\r\n module,\r\n action,\r\n stack,\r\n context,\r\n timestamp: new Date().toISOString(),\r\n });\r\n\r\n await this.checkIfMessagesShouldBeWritten(); // Immediate check on buffer size\r\n }\r\n\r\n /**\r\n * Check if messages should be written\r\n */\r\n protected async checkIfMessagesShouldBeWritten() {\r\n if (this.messages.length >= this.maxMessagesToWrite || Date.now() - this.lastWriteTime > 5000) {\r\n await this.writeMessagesToFile();\r\n }\r\n }\r\n\r\n /**\r\n * Should be called after messages are saved\r\n */\r\n protected onSave() {\r\n this.messages = [];\r\n this.groupedMessages = {};\r\n this.isWriting = false;\r\n this.lastWriteTime = Date.now();\r\n }\r\n\r\n /**\r\n * Check if messages should be grouped\r\n */\r\n protected get messagedShouldBeGrouped(): boolean {\r\n return Number(this.config(\"groupBy\")?.length) > 0;\r\n }\r\n\r\n /**\r\n * Write messages to the file\r\n */\r\n protected async writeMessagesToFile() {\r\n if (this.messages.length === 0 || this.isWriting || !this.isInitialized) return;\r\n\r\n this.isWriting = true;\r\n\r\n if (this.messagedShouldBeGrouped) {\r\n return await this.writeGroupedMessagesToFile();\r\n }\r\n\r\n await this.checkAndRotateFile(); // Ensure we check file size before writing\r\n\r\n try {\r\n await this.write(this.filePath, this.content);\r\n this.onSave();\r\n } catch (error) {\r\n console.error(\"Failed to write log:\", error);\r\n // Implement fallback logic here\r\n this.isWriting = false;\r\n }\r\n }\r\n\r\n /**\r\n * Write grouped messages to the file\r\n */\r\n protected async writeGroupedMessagesToFile(): Promise<void> {\r\n // first step, is to group the messages\r\n this.prepareGroupedMessages();\r\n\r\n // now each key in the grouped messages, represents the directory path that should extend the storage path\r\n for (const key in this.groupedMessages) {\r\n const directoryPath = path.join(this.storagePath, key);\r\n\r\n await ensureDirectoryAsync(directoryPath);\r\n\r\n const filePath = path.join(directoryPath, `${this.fileName}.${this.extension}`);\r\n\r\n await this.checkAndRotateFile(filePath); // Ensure we check file size before writing\r\n\r\n const content = this.groupedMessages[key].map((message) => message.content).join(EOL) + EOL;\r\n\r\n try {\r\n await this.write(filePath, content);\r\n } catch (error) {\r\n console.error(\"Failed to write log:\", error);\r\n }\r\n }\r\n\r\n this.onSave();\r\n this.isWriting = false;\r\n }\r\n\r\n /**\r\n * Prepare grouped messages\r\n */\r\n protected prepareGroupedMessages(): void {\r\n this.messages.forEach((message) => {\r\n const key = this.config(\"groupBy\")!\r\n .map((groupKey) => encodeURIComponent(message[groupKey]))\r\n .join(\"/\");\r\n\r\n this.groupedMessages[key] = this.groupedMessages[key] || [];\r\n this.groupedMessages[key].push(message);\r\n });\r\n }\r\n\r\n /**\r\n * Start writing to the file\r\n */\r\n protected async write(filePath: string, content: string) {\r\n return new Promise((resolve, reject) => {\r\n const writer = fs.createWriteStream(filePath, { flags: \"a\" });\r\n\r\n writer.write(content, (error) => {\r\n writer.end();\r\n if (error) {\r\n reject(error);\r\n } else {\r\n resolve(true);\r\n }\r\n });\r\n });\r\n }\r\n}\r\n"],"mappings":";;;;;;;;AAmFA,IAAa,UAAb,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AAgB,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"}
|
package/esm/channels/index.mjs
CHANGED
|
@@ -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 ../@warlock.js/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":["../../../../../../../@warlock.js/logger/src/channels/json-file-log.ts"],"mappings":";;;;cAQa,WAAA,SAAoB,OAAA,YAAmB,WAAA;;AAApD;;EAIS,IAAA;EAuDgB;;;EAAA,IAlDZ,SAAA;EAToB;;;EAgBxB,SAAA;EAhBwB;;;EA2DlB,GAAA,CAAI,IAAA,EAAM,WAAA,GAAW,OAAA;EA3C3B;;;EAAA,UA4ES,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 ../@warlock.js/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":["../../../../../../../@warlock.js/logger/src/channels/json-file-log.ts"],"sourcesContent":["import { ensureDirectoryAsync, fileExistsAsync, getJsonFileAsync } from \"@warlock.js/fs\";\r\nimport dayjs from \"dayjs\";\r\nimport fs from \"fs\";\r\nimport path from \"path\";\r\nimport type { LogContract, LogMessage, LoggingData } from \"../types\";\r\nimport { safeJsonStringify } from \"../utils/safe-json-stringify\";\r\nimport { FileLog } from \"./file-log\";\r\n\r\nexport class JSONFileLog extends FileLog implements LogContract {\r\n /**\r\n * {@inheritdoc}\r\n */\r\n public name = \"fileJson\";\r\n\r\n /**\r\n * Get file extension\r\n */\r\n public get extension(): string {\r\n return \"json\";\r\n }\r\n\r\n /**\r\n * Synchronously flush messages\r\n */\r\n public flushSync(): void {\r\n if (this.messages.length === 0 && Object.keys(this.groupedMessages).length === 0) return;\r\n\r\n if (this.messagedShouldBeGrouped) {\r\n this.prepareGroupedMessages();\r\n for (const key in this.groupedMessages) {\r\n const directoryPath = path.join(this.storagePath, key);\r\n fs.mkdirSync(directoryPath, { recursive: true });\r\n const filePath = path.join(directoryPath, `${this.fileName}.${this.extension}`);\r\n\r\n let fileContents = { messages: [] as any[] };\r\n if (fs.existsSync(filePath)) {\r\n try {\r\n fileContents = JSON.parse(fs.readFileSync(filePath, \"utf-8\"));\r\n if (!Array.isArray(fileContents.messages)) fileContents.messages = [];\r\n } catch (e) {\r\n fileContents = { messages: [] };\r\n }\r\n }\r\n fileContents.messages.push(...this.groupedMessages[key]);\r\n fs.writeFileSync(filePath, safeJsonStringify(fileContents, 2));\r\n }\r\n } else {\r\n fs.mkdirSync(this.storagePath, { recursive: true });\r\n let fileContents = { messages: [] as any[] };\r\n if (fs.existsSync(this.filePath)) {\r\n try {\r\n fileContents = JSON.parse(fs.readFileSync(this.filePath, \"utf-8\"));\r\n if (!Array.isArray(fileContents.messages)) fileContents.messages = [];\r\n } catch (e) {\r\n fileContents = { messages: [] };\r\n }\r\n }\r\n fileContents.messages.push(...this.messages);\r\n fs.writeFileSync(this.filePath, safeJsonStringify(fileContents, 2));\r\n }\r\n\r\n this.onSave();\r\n }\r\n\r\n /**\r\n * {@inheritdoc}\r\n */\r\n public async log(data: LoggingData) {\r\n let stack: string[] | undefined;\r\n\r\n if (data.message instanceof Error) {\r\n stack = data.message.stack?.split(\"\\n\");\r\n data.message = data.message.message;\r\n }\r\n\r\n const { module, action, message, type: level, context } = data;\r\n\r\n if (!this.shouldBeLogged(data)) return;\r\n\r\n const { date: dateFormat, time } = this.getDateAndTimeFormat();\r\n\r\n const date = dayjs().format(dateFormat + \" \" + time);\r\n\r\n this.messages.push({\r\n content: message,\r\n level,\r\n date,\r\n module,\r\n action,\r\n stack,\r\n context,\r\n timestamp: new Date().toISOString(),\r\n } as LogMessage);\r\n\r\n await this.checkIfMessagesShouldBeWritten(); // Immediate check on buffer size\r\n }\r\n\r\n /**\r\n * Write messages to the file\r\n */\r\n protected async writeMessagesToFile(): Promise<void> {\r\n if (this.messages.length === 0 || this.isWriting || !this.isInitialized) return;\r\n\r\n this.isWriting = true;\r\n\r\n if (this.messagedShouldBeGrouped) {\r\n return await this.writeGroupedMessagesToFile();\r\n }\r\n\r\n await this.checkAndRotateFile(); // Ensure file rotation is handled\r\n\r\n let fileContents = { messages: [] as any[] };\r\n\r\n if (await fileExistsAsync(this.filePath)) {\r\n try {\r\n fileContents = (await getJsonFileAsync(this.filePath)) as { messages: any[] };\r\n } catch (error) {\r\n console.error(\"Error reading log file, reinitializing:\", error);\r\n fileContents = { messages: [] }; // Reinitialize the file if corrupted\r\n }\r\n } else {\r\n fileContents = { messages: [] }; // Reinitialize the file if corrupted\r\n }\r\n\r\n fileContents.messages.push(...this.messages);\r\n\r\n try {\r\n await fs.promises.writeFile(this.filePath, safeJsonStringify(fileContents, 2));\r\n\r\n this.onSave();\r\n } catch (error) {\r\n console.error(\"Failed to write log:\", error);\r\n // Implement fallback logic here\r\n this.isWriting = false;\r\n }\r\n }\r\n\r\n /**\r\n * Write grouped messages to the file\r\n */\r\n protected async writeGroupedMessagesToFile(): Promise<void> {\r\n // first step, is to group the messages\r\n this.prepareGroupedMessages();\r\n\r\n // now each key in the grouped messages, represents the directory path that should extend the storage path\r\n for (const key in this.groupedMessages) {\r\n const directoryPath = path.join(this.storagePath, key);\r\n\r\n await ensureDirectoryAsync(directoryPath);\r\n\r\n const filePath = path.join(directoryPath, `${this.fileName}.${this.extension}`);\r\n\r\n await this.checkAndRotateFile(filePath); // Ensure we check file size before writing\r\n\r\n let fileContents: { messages: any[] } = { messages: [] };\r\n if (await fileExistsAsync(filePath)) {\r\n try {\r\n fileContents = (await getJsonFileAsync(filePath)) as { messages: any[] };\r\n } catch (error) {\r\n console.error(\"Error reading log file, reinitializing:\", error);\r\n fileContents = { messages: [] };\r\n }\r\n } else {\r\n fileContents = { messages: [] };\r\n }\r\n\r\n fileContents.messages.push(...this.groupedMessages[key]);\r\n\r\n try {\r\n await fs.promises.writeFile(filePath, safeJsonStringify(fileContents, 2));\r\n } catch (error) {\r\n console.error(\"Failed to write log:\", error);\r\n this.isWriting = false;\r\n }\r\n }\r\n\r\n this.onSave();\r\n }\r\n}\r\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;GAC5B,KAAK,MAAM,OAAO,KAAK,iBAAiB;IACtC,MAAM,gBAAgB,KAAK,KAAK,KAAK,aAAa,GAAG;IACrD,GAAG,UAAU,eAAe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EAAE;GACvD,IAAI,MAAM,gBAAgB,QAAQ,GAChC,IAAI;IACF,eAAgB,MAAM,iBAAiB,QAAQ;GACjD,SAAS,OAAO;IACd,QAAQ,MAAM,2CAA2C,KAAK;IAC9D,eAAe,EAAE,UAAU,CAAC,EAAE;GAChC;QAEA,eAAe,EAAE,UAAU,CAAC,EAAE;GAGhC,aAAa,SAAS,KAAK,GAAG,KAAK,gBAAgB,IAAI;GAEvD,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"}
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import { BasicLogConfigurations, LogLevel, LoggingData } from "../types.mjs";
|
|
2
|
+
import { LogChannel } from "../log-channel.mjs";
|
|
3
|
+
|
|
4
|
+
//#region ../@warlock.js/logger/src/channels/sentry-log.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* Sentry severity levels — the `@sentry/node` `SeverityLevel` union.
|
|
7
|
+
*/
|
|
8
|
+
type SentrySeverityLevel = "fatal" | "error" | "warning" | "log" | "info" | "debug";
|
|
9
|
+
/**
|
|
10
|
+
* The Sentry `Scope` surface used while building a single event.
|
|
11
|
+
*/
|
|
12
|
+
interface SentryScopeLike {
|
|
13
|
+
setLevel(level: SentrySeverityLevel): void;
|
|
14
|
+
setTags(tags: Record<string, string>): void;
|
|
15
|
+
setContext(name: string, context: Record<string, unknown> | null): void;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* A Sentry breadcrumb, as passed to `addBreadcrumb`.
|
|
19
|
+
*/
|
|
20
|
+
type SentryBreadcrumb = {
|
|
21
|
+
category?: string;
|
|
22
|
+
message?: string;
|
|
23
|
+
level?: SentrySeverityLevel;
|
|
24
|
+
data?: Record<string, unknown>;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* The subset of the `@sentry/node` API `SentryLog` calls. The `@sentry/node`
|
|
28
|
+
* namespace satisfies this shape, so an app can pass it straight through as
|
|
29
|
+
* `client`; a test (or a custom forwarder) can supply a compatible stand-in.
|
|
30
|
+
*/
|
|
31
|
+
interface SentryForwarder {
|
|
32
|
+
captureException(exception: unknown): string;
|
|
33
|
+
captureMessage(message: string, level?: SentrySeverityLevel): string;
|
|
34
|
+
addBreadcrumb(breadcrumb: SentryBreadcrumb): void;
|
|
35
|
+
withScope(callback: (scope: SentryScopeLike) => void): void;
|
|
36
|
+
flush(timeout?: number): Promise<boolean>;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Sentry initialization options. Mirrors the common `@sentry/node` `NodeOptions`
|
|
40
|
+
* fields; the index signature keeps any other SDK option valid without coupling
|
|
41
|
+
* to the SDK's types.
|
|
42
|
+
*/
|
|
43
|
+
type SentryInitOptions = {
|
|
44
|
+
dsn?: string;
|
|
45
|
+
environment?: string;
|
|
46
|
+
release?: string;
|
|
47
|
+
sampleRate?: number;
|
|
48
|
+
[key: string]: unknown;
|
|
49
|
+
};
|
|
50
|
+
type SentryLogConfig = BasicLogConfigurations & {
|
|
51
|
+
/**
|
|
52
|
+
* Reuse an already-initialized Sentry instance — typically the `@sentry/node`
|
|
53
|
+
* namespace from an app that already calls `Sentry.init(...)`. When set, the
|
|
54
|
+
* channel forwards through it and never imports or re-initializes the SDK.
|
|
55
|
+
*/
|
|
56
|
+
client?: SentryForwarder;
|
|
57
|
+
/**
|
|
58
|
+
* Initialize Sentry from these options instead of reusing a host client. The
|
|
59
|
+
* channel lazily imports `@sentry/node` and calls `Sentry.init(options)` once,
|
|
60
|
+
* guarded so it never clobbers an existing client.
|
|
61
|
+
*/
|
|
62
|
+
options?: SentryInitOptions;
|
|
63
|
+
/**
|
|
64
|
+
* Levels delivered as Sentry *events* (these consume the error quota). Every
|
|
65
|
+
* other level is recorded as a breadcrumb that rides along with the next
|
|
66
|
+
* event, costing no quota.
|
|
67
|
+
*
|
|
68
|
+
* @default ["fatal", "error", "warn"]
|
|
69
|
+
*/
|
|
70
|
+
eventLevels?: LogLevel[];
|
|
71
|
+
/**
|
|
72
|
+
* Milliseconds `flush()` waits for the transport to drain on shutdown.
|
|
73
|
+
*
|
|
74
|
+
* @default 2000
|
|
75
|
+
*/
|
|
76
|
+
flushTimeout?: number;
|
|
77
|
+
};
|
|
78
|
+
/**
|
|
79
|
+
* Forwards log entries to Sentry.
|
|
80
|
+
*
|
|
81
|
+
* Entries at an `eventLevels` level (`error` / `warn` by default) become Sentry
|
|
82
|
+
* **events**: an `Error` message via `captureException` (preserving the real
|
|
83
|
+
* stack), any other message via `captureMessage`. Every other level becomes a
|
|
84
|
+
* **breadcrumb** — buffered and attached to the next event, consuming no error
|
|
85
|
+
* quota. `module` / `action` are attached as searchable tags and the entry's
|
|
86
|
+
* `context` as a structured Sentry context.
|
|
87
|
+
*
|
|
88
|
+
* The SDK is an optional peer: pass an existing `client` (reused as-is) or
|
|
89
|
+
* `options` (the channel lazily imports `@sentry/node` and initializes it). On
|
|
90
|
+
* graceful shutdown, `await log.flush()` drains pending events via
|
|
91
|
+
* `Sentry.flush(timeout)`.
|
|
92
|
+
*
|
|
93
|
+
* @example
|
|
94
|
+
* // Existing app — reuse the initialized Sentry client
|
|
95
|
+
* import * as Sentry from "@sentry/node";
|
|
96
|
+
* log.addChannel(new SentryLog({ client: Sentry }));
|
|
97
|
+
*
|
|
98
|
+
* @example
|
|
99
|
+
* // New app — let the channel initialize Sentry
|
|
100
|
+
* log.addChannel(new SentryLog({ options: { dsn: process.env.SENTRY_DSN } }));
|
|
101
|
+
*/
|
|
102
|
+
declare class SentryLog extends LogChannel<SentryLogConfig> {
|
|
103
|
+
/**
|
|
104
|
+
* {@inheritdoc}
|
|
105
|
+
*/
|
|
106
|
+
name: string;
|
|
107
|
+
/**
|
|
108
|
+
* {@inheritdoc}
|
|
109
|
+
*/
|
|
110
|
+
description: string;
|
|
111
|
+
/**
|
|
112
|
+
* {@inheritdoc}
|
|
113
|
+
*/
|
|
114
|
+
protected defaultConfigurations: SentryLogConfig;
|
|
115
|
+
/**
|
|
116
|
+
* The resolved forwarder — the injected `client` or the lazily-imported
|
|
117
|
+
* `@sentry/node` namespace. `undefined` until `init()` resolves, and when the
|
|
118
|
+
* SDK is absent (then `log()` surfaces the install message once).
|
|
119
|
+
*/
|
|
120
|
+
private sentry?;
|
|
121
|
+
/**
|
|
122
|
+
* Guards the one-time "@sentry/node is not installed" notice so a missing SDK
|
|
123
|
+
* doesn't spam stderr on every entry.
|
|
124
|
+
*/
|
|
125
|
+
private warnedMissing;
|
|
126
|
+
/**
|
|
127
|
+
* Resolve an injected `client` (the Sentry namespace) **synchronously**, so an
|
|
128
|
+
* entry logged on the same tick as construction — e.g. at app boot, before
|
|
129
|
+
* the base schedules `init()` on the next tick via `setTimeout(0)` — is not
|
|
130
|
+
* silently dropped. The `options` (lazy-import) path is inherently async and
|
|
131
|
+
* still resolves in `init()`.
|
|
132
|
+
*/
|
|
133
|
+
constructor(configurations?: SentryLogConfig);
|
|
134
|
+
/**
|
|
135
|
+
* Resolve the forwarder: reuse the injected client, otherwise lazily import
|
|
136
|
+
* `@sentry/node` and (only when explicit `options` are supplied and no client
|
|
137
|
+
* exists yet) initialize it. Never throws — the base runs `init()` inside an
|
|
138
|
+
* un-awaited `setTimeout`, so a throw would become an unhandled rejection and
|
|
139
|
+
* `isInitialized` would never flip; a missing SDK is reported from `log()`.
|
|
140
|
+
*/
|
|
141
|
+
protected init(): Promise<void>;
|
|
142
|
+
/**
|
|
143
|
+
* {@inheritdoc}
|
|
144
|
+
*/
|
|
145
|
+
log(data: LoggingData): Promise<void>;
|
|
146
|
+
/**
|
|
147
|
+
* Drain pending Sentry events. Bounded by `flushTimeout` so an unreachable
|
|
148
|
+
* Sentry can never hang a graceful shutdown. No-op when the SDK is absent.
|
|
149
|
+
*/
|
|
150
|
+
flush(): Promise<void>;
|
|
151
|
+
/**
|
|
152
|
+
* Whether the level should be sent as a Sentry event (vs a breadcrumb).
|
|
153
|
+
*/
|
|
154
|
+
private isEventLevel;
|
|
155
|
+
/**
|
|
156
|
+
* Send an entry as a Sentry event. An `Error` message goes through
|
|
157
|
+
* `captureException` so Sentry parses the real stack and groups properly;
|
|
158
|
+
* any other message goes through `captureMessage`. `module` / `action` are
|
|
159
|
+
* attached as tags and `context` as a structured context, scoped to this
|
|
160
|
+
* event only via `withScope`.
|
|
161
|
+
*/
|
|
162
|
+
private captureEvent;
|
|
163
|
+
/**
|
|
164
|
+
* Map a logger level to a Sentry severity. `success` has no Sentry
|
|
165
|
+
* equivalent, so it is reported as informational.
|
|
166
|
+
*/
|
|
167
|
+
private toSentryLevel;
|
|
168
|
+
/**
|
|
169
|
+
* Coerce a message into the string Sentry's APIs expect — an `Error`'s
|
|
170
|
+
* `.message`, a string as-is, anything else safely JSON-serialized.
|
|
171
|
+
*/
|
|
172
|
+
private toText;
|
|
173
|
+
/**
|
|
174
|
+
* Surface the install instructions exactly once when the SDK is absent. The
|
|
175
|
+
* logger can't log through itself here, so this writes to stderr — matching
|
|
176
|
+
* how the file channels report write failures.
|
|
177
|
+
*/
|
|
178
|
+
private reportMissingSdk;
|
|
179
|
+
}
|
|
180
|
+
//#endregion
|
|
181
|
+
export { SentryBreadcrumb, SentryForwarder, SentryInitOptions, SentryLog, SentryLogConfig, SentryScopeLike };
|
|
182
|
+
//# sourceMappingURL=sentry-log.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sentry-log.d.mts","names":[],"sources":["../../../../../../../@warlock.js/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;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.js/logger/src/channels/sentry-log.ts
|
|
5
|
+
let Sentry;
|
|
6
|
+
let isModuleExists = null;
|
|
7
|
+
let loadingPromise;
|
|
8
|
+
const SENTRY_INSTALL_INSTRUCTIONS = `
|
|
9
|
+
The Sentry log channel requires the @sentry/node package.
|
|
10
|
+
Install it with:
|
|
11
|
+
|
|
12
|
+
npm install @sentry/node
|
|
13
|
+
|
|
14
|
+
Or with your preferred package manager:
|
|
15
|
+
|
|
16
|
+
pnpm add @sentry/node
|
|
17
|
+
yarn add @sentry/node
|
|
18
|
+
`.trim();
|
|
19
|
+
/**
|
|
20
|
+
* Load @sentry/node once, lazily and concurrency-safely. A bare catch maps any
|
|
21
|
+
* import failure to "not installed" — the curated install message surfaces at
|
|
22
|
+
* `log()` time, never as a boot-time module-resolution crash.
|
|
23
|
+
*/
|
|
24
|
+
function loadSentry() {
|
|
25
|
+
if (isModuleExists !== null) return Promise.resolve();
|
|
26
|
+
if (loadingPromise) return loadingPromise;
|
|
27
|
+
loadingPromise = (async () => {
|
|
28
|
+
try {
|
|
29
|
+
Sentry = await import("@sentry/node");
|
|
30
|
+
isModuleExists = true;
|
|
31
|
+
} catch {
|
|
32
|
+
isModuleExists = false;
|
|
33
|
+
}
|
|
34
|
+
})();
|
|
35
|
+
return loadingPromise;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Forwards log entries to Sentry.
|
|
39
|
+
*
|
|
40
|
+
* Entries at an `eventLevels` level (`error` / `warn` by default) become Sentry
|
|
41
|
+
* **events**: an `Error` message via `captureException` (preserving the real
|
|
42
|
+
* stack), any other message via `captureMessage`. Every other level becomes a
|
|
43
|
+
* **breadcrumb** — buffered and attached to the next event, consuming no error
|
|
44
|
+
* quota. `module` / `action` are attached as searchable tags and the entry's
|
|
45
|
+
* `context` as a structured Sentry context.
|
|
46
|
+
*
|
|
47
|
+
* The SDK is an optional peer: pass an existing `client` (reused as-is) or
|
|
48
|
+
* `options` (the channel lazily imports `@sentry/node` and initializes it). On
|
|
49
|
+
* graceful shutdown, `await log.flush()` drains pending events via
|
|
50
|
+
* `Sentry.flush(timeout)`.
|
|
51
|
+
*
|
|
52
|
+
* @example
|
|
53
|
+
* // Existing app — reuse the initialized Sentry client
|
|
54
|
+
* import * as Sentry from "@sentry/node";
|
|
55
|
+
* log.addChannel(new SentryLog({ client: Sentry }));
|
|
56
|
+
*
|
|
57
|
+
* @example
|
|
58
|
+
* // New app — let the channel initialize Sentry
|
|
59
|
+
* log.addChannel(new SentryLog({ options: { dsn: process.env.SENTRY_DSN } }));
|
|
60
|
+
*/
|
|
61
|
+
var SentryLog = class extends LogChannel {
|
|
62
|
+
/**
|
|
63
|
+
* Resolve an injected `client` (the Sentry namespace) **synchronously**, so an
|
|
64
|
+
* entry logged on the same tick as construction — e.g. at app boot, before
|
|
65
|
+
* the base schedules `init()` on the next tick via `setTimeout(0)` — is not
|
|
66
|
+
* silently dropped. The `options` (lazy-import) path is inherently async and
|
|
67
|
+
* still resolves in `init()`.
|
|
68
|
+
*/
|
|
69
|
+
constructor(configurations) {
|
|
70
|
+
super(configurations);
|
|
71
|
+
this.name = "sentry";
|
|
72
|
+
this.description = "Forwards entries to Sentry as events (error/warn) or breadcrumbs (everything else)";
|
|
73
|
+
this.defaultConfigurations = {
|
|
74
|
+
eventLevels: [
|
|
75
|
+
"fatal",
|
|
76
|
+
"error",
|
|
77
|
+
"warn"
|
|
78
|
+
],
|
|
79
|
+
flushTimeout: 2e3
|
|
80
|
+
};
|
|
81
|
+
this.warnedMissing = false;
|
|
82
|
+
const injected = this.config("client");
|
|
83
|
+
if (injected) this.sentry = injected;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Resolve the forwarder: reuse the injected client, otherwise lazily import
|
|
87
|
+
* `@sentry/node` and (only when explicit `options` are supplied and no client
|
|
88
|
+
* exists yet) initialize it. Never throws — the base runs `init()` inside an
|
|
89
|
+
* un-awaited `setTimeout`, so a throw would become an unhandled rejection and
|
|
90
|
+
* `isInitialized` would never flip; a missing SDK is reported from `log()`.
|
|
91
|
+
*/
|
|
92
|
+
async init() {
|
|
93
|
+
const injected = this.config("client");
|
|
94
|
+
if (injected) {
|
|
95
|
+
this.sentry = injected;
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
await loadSentry();
|
|
99
|
+
if (!Sentry) return;
|
|
100
|
+
const options = this.config("options");
|
|
101
|
+
if (options && !Sentry.getClient()) Sentry.init(options);
|
|
102
|
+
this.sentry = Sentry;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* {@inheritdoc}
|
|
106
|
+
*/
|
|
107
|
+
async log(data) {
|
|
108
|
+
if (!this.shouldBeLogged(data)) return;
|
|
109
|
+
if (isModuleExists === null) await loadSentry();
|
|
110
|
+
if (!this.sentry) {
|
|
111
|
+
this.reportMissingSdk();
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
const { module, action, message, type: level, context } = data;
|
|
115
|
+
if (this.isEventLevel(level)) {
|
|
116
|
+
this.captureEvent(this.sentry, {
|
|
117
|
+
module,
|
|
118
|
+
action,
|
|
119
|
+
message,
|
|
120
|
+
level,
|
|
121
|
+
context
|
|
122
|
+
});
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
this.sentry.addBreadcrumb({
|
|
126
|
+
category: module,
|
|
127
|
+
message: this.toText(message),
|
|
128
|
+
level: this.toSentryLevel(level),
|
|
129
|
+
data: context
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Drain pending Sentry events. Bounded by `flushTimeout` so an unreachable
|
|
134
|
+
* Sentry can never hang a graceful shutdown. No-op when the SDK is absent.
|
|
135
|
+
*/
|
|
136
|
+
async flush() {
|
|
137
|
+
if (!this.sentry) return;
|
|
138
|
+
await this.sentry.flush(this.config("flushTimeout"));
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Whether the level should be sent as a Sentry event (vs a breadcrumb).
|
|
142
|
+
*/
|
|
143
|
+
isEventLevel(level) {
|
|
144
|
+
return Boolean(this.config("eventLevels")?.includes(level));
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Send an entry as a Sentry event. An `Error` message goes through
|
|
148
|
+
* `captureException` so Sentry parses the real stack and groups properly;
|
|
149
|
+
* any other message goes through `captureMessage`. `module` / `action` are
|
|
150
|
+
* attached as tags and `context` as a structured context, scoped to this
|
|
151
|
+
* event only via `withScope`.
|
|
152
|
+
*/
|
|
153
|
+
captureEvent(sentry, entry) {
|
|
154
|
+
const { module, action, message, level, context } = entry;
|
|
155
|
+
const sentryLevel = this.toSentryLevel(level);
|
|
156
|
+
sentry.withScope((scope) => {
|
|
157
|
+
scope.setLevel(sentryLevel);
|
|
158
|
+
scope.setTags({
|
|
159
|
+
module,
|
|
160
|
+
action
|
|
161
|
+
});
|
|
162
|
+
if (context) scope.setContext("context", context);
|
|
163
|
+
if (message instanceof Error) sentry.captureException(message);
|
|
164
|
+
else sentry.captureMessage(this.toText(message), sentryLevel);
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Map a logger level to a Sentry severity. `success` has no Sentry
|
|
169
|
+
* equivalent, so it is reported as informational.
|
|
170
|
+
*/
|
|
171
|
+
toSentryLevel(level) {
|
|
172
|
+
switch (level) {
|
|
173
|
+
case "warn": return "warning";
|
|
174
|
+
case "success": return "info";
|
|
175
|
+
default: return level;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Coerce a message into the string Sentry's APIs expect — an `Error`'s
|
|
180
|
+
* `.message`, a string as-is, anything else safely JSON-serialized.
|
|
181
|
+
*/
|
|
182
|
+
toText(message) {
|
|
183
|
+
if (typeof message === "string") return message;
|
|
184
|
+
if (message instanceof Error) return message.message;
|
|
185
|
+
return safeJsonStringify(message);
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Surface the install instructions exactly once when the SDK is absent. The
|
|
189
|
+
* logger can't log through itself here, so this writes to stderr — matching
|
|
190
|
+
* how the file channels report write failures.
|
|
191
|
+
*/
|
|
192
|
+
reportMissingSdk() {
|
|
193
|
+
if (isModuleExists === false && !this.warnedMissing) {
|
|
194
|
+
this.warnedMissing = true;
|
|
195
|
+
console.error(SENTRY_INSTALL_INSTRUCTIONS);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
//#endregion
|
|
201
|
+
export { SentryLog };
|
|
202
|
+
//# sourceMappingURL=sentry-log.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sentry-log.mjs","names":[],"sources":["../../../../../../../@warlock.js/logger/src/channels/sentry-log.ts"],"sourcesContent":["import { LogChannel } from \"../log-channel\";\r\nimport type { BasicLogConfigurations, LoggingData, LogLevel } from \"../types\";\r\nimport { safeJsonStringify } from \"../utils/safe-json-stringify\";\r\n\r\n// ── @sentry/node as an optional peer ─────────────────────────────────────────\r\n// @sentry/node is referenced ONLY through the local minimal types below — never\r\n// via `typeof import(\"@sentry/node\")`. This package is served as source\r\n// (`main` → `./src/index.ts`), so its `.ts` becomes part of a consumer's TS\r\n// program; a static type reference to the SDK would force module resolution and\r\n// break every consumer who (correctly) never installs the optional peer with a\r\n// TS2307 \"cannot find module\". The runtime import uses an indirect specifier for\r\n// the same reason, and its result is cast to these shapes. The shapes mirror the\r\n// stable `@sentry/node` public API (unchanged across v8–v10).\r\n\r\n/**\r\n * Sentry severity levels — the `@sentry/node` `SeverityLevel` union.\r\n */\r\ntype SentrySeverityLevel =\r\n | \"fatal\"\r\n | \"error\"\r\n | \"warning\"\r\n | \"log\"\r\n | \"info\"\r\n | \"debug\";\r\n\r\n/**\r\n * The Sentry `Scope` surface used while building a single event.\r\n */\r\nexport interface SentryScopeLike {\r\n setLevel(level: SentrySeverityLevel): void;\r\n setTags(tags: Record<string, string>): void;\r\n setContext(name: string, context: Record<string, unknown> | null): void;\r\n}\r\n\r\n/**\r\n * A Sentry breadcrumb, as passed to `addBreadcrumb`.\r\n */\r\nexport type SentryBreadcrumb = {\r\n category?: string;\r\n message?: string;\r\n level?: SentrySeverityLevel;\r\n data?: Record<string, unknown>;\r\n};\r\n\r\n/**\r\n * The subset of the `@sentry/node` API `SentryLog` calls. The `@sentry/node`\r\n * namespace satisfies this shape, so an app can pass it straight through as\r\n * `client`; a test (or a custom forwarder) can supply a compatible stand-in.\r\n */\r\nexport interface SentryForwarder {\r\n captureException(exception: unknown): string;\r\n captureMessage(message: string, level?: SentrySeverityLevel): string;\r\n addBreadcrumb(breadcrumb: SentryBreadcrumb): void;\r\n withScope(callback: (scope: SentryScopeLike) => void): void;\r\n flush(timeout?: number): Promise<boolean>;\r\n}\r\n\r\n/**\r\n * Sentry initialization options. Mirrors the common `@sentry/node` `NodeOptions`\r\n * fields; the index signature keeps any other SDK option valid without coupling\r\n * to the SDK's types.\r\n */\r\nexport type SentryInitOptions = {\r\n dsn?: string;\r\n environment?: string;\r\n release?: string;\r\n sampleRate?: number;\r\n [key: string]: unknown;\r\n};\r\n\r\n/**\r\n * The lazily-imported `@sentry/node` namespace surface — the forwarder plus the\r\n * lifecycle calls the channel uses when it owns initialization.\r\n */\r\ninterface SentryNamespace extends SentryForwarder {\r\n init(options?: SentryInitOptions): unknown;\r\n getClient(): unknown;\r\n}\r\n\r\nlet Sentry: SentryNamespace | undefined;\r\nlet isModuleExists: boolean | null = null;\r\nlet loadingPromise: Promise<void> | undefined;\r\n\r\nconst SENTRY_INSTALL_INSTRUCTIONS = `\r\nThe Sentry log channel requires the @sentry/node package.\r\nInstall it with:\r\n\r\n npm install @sentry/node\r\n\r\nOr with your preferred package manager:\r\n\r\n pnpm add @sentry/node\r\n yarn add @sentry/node\r\n`.trim();\r\n\r\n/**\r\n * Load @sentry/node once, lazily and concurrency-safely. A bare catch maps any\r\n * import failure to \"not installed\" — the curated install message surfaces at\r\n * `log()` time, never as a boot-time module-resolution crash.\r\n */\r\nfunction loadSentry(): Promise<void> {\r\n if (isModuleExists !== null) {\r\n return Promise.resolve();\r\n }\r\n\r\n if (loadingPromise) {\r\n return loadingPromise;\r\n }\r\n\r\n loadingPromise = (async () => {\r\n try {\r\n // Indirect specifier (typed `string`, not a literal) so TypeScript never\r\n // statically resolves the optional peer — see the file header.\r\n const sentryModule: string = \"@sentry/node\";\r\n Sentry = (await import(sentryModule)) as unknown as SentryNamespace;\r\n isModuleExists = true;\r\n } catch {\r\n isModuleExists = false;\r\n }\r\n })();\r\n\r\n return loadingPromise;\r\n}\r\n\r\nexport type SentryLogConfig = BasicLogConfigurations & {\r\n /**\r\n * Reuse an already-initialized Sentry instance — typically the `@sentry/node`\r\n * namespace from an app that already calls `Sentry.init(...)`. When set, the\r\n * channel forwards through it and never imports or re-initializes the SDK.\r\n */\r\n client?: SentryForwarder;\r\n /**\r\n * Initialize Sentry from these options instead of reusing a host client. The\r\n * channel lazily imports `@sentry/node` and calls `Sentry.init(options)` once,\r\n * guarded so it never clobbers an existing client.\r\n */\r\n options?: SentryInitOptions;\r\n /**\r\n * Levels delivered as Sentry *events* (these consume the error quota). Every\r\n * other level is recorded as a breadcrumb that rides along with the next\r\n * event, costing no quota.\r\n *\r\n * @default [\"fatal\", \"error\", \"warn\"]\r\n */\r\n eventLevels?: LogLevel[];\r\n /**\r\n * Milliseconds `flush()` waits for the transport to drain on shutdown.\r\n *\r\n * @default 2000\r\n */\r\n flushTimeout?: number;\r\n};\r\n\r\n/**\r\n * Forwards log entries to Sentry.\r\n *\r\n * Entries at an `eventLevels` level (`error` / `warn` by default) become Sentry\r\n * **events**: an `Error` message via `captureException` (preserving the real\r\n * stack), any other message via `captureMessage`. Every other level becomes a\r\n * **breadcrumb** — buffered and attached to the next event, consuming no error\r\n * quota. `module` / `action` are attached as searchable tags and the entry's\r\n * `context` as a structured Sentry context.\r\n *\r\n * The SDK is an optional peer: pass an existing `client` (reused as-is) or\r\n * `options` (the channel lazily imports `@sentry/node` and initializes it). On\r\n * graceful shutdown, `await log.flush()` drains pending events via\r\n * `Sentry.flush(timeout)`.\r\n *\r\n * @example\r\n * // Existing app — reuse the initialized Sentry client\r\n * import * as Sentry from \"@sentry/node\";\r\n * log.addChannel(new SentryLog({ client: Sentry }));\r\n *\r\n * @example\r\n * // New app — let the channel initialize Sentry\r\n * log.addChannel(new SentryLog({ options: { dsn: process.env.SENTRY_DSN } }));\r\n */\r\nexport class SentryLog extends LogChannel<SentryLogConfig> {\r\n /**\r\n * {@inheritdoc}\r\n */\r\n public name = \"sentry\";\r\n\r\n /**\r\n * {@inheritdoc}\r\n */\r\n public description =\r\n \"Forwards entries to Sentry as events (error/warn) or breadcrumbs (everything else)\";\r\n\r\n /**\r\n * {@inheritdoc}\r\n */\r\n protected defaultConfigurations: SentryLogConfig = {\r\n eventLevels: [\"fatal\", \"error\", \"warn\"],\r\n flushTimeout: 2_000,\r\n };\r\n\r\n /**\r\n * The resolved forwarder — the injected `client` or the lazily-imported\r\n * `@sentry/node` namespace. `undefined` until `init()` resolves, and when the\r\n * SDK is absent (then `log()` surfaces the install message once).\r\n */\r\n private sentry?: SentryForwarder;\r\n\r\n /**\r\n * Guards the one-time \"@sentry/node is not installed\" notice so a missing SDK\r\n * doesn't spam stderr on every entry.\r\n */\r\n private warnedMissing = false;\r\n\r\n /**\r\n * Resolve an injected `client` (the Sentry namespace) **synchronously**, so an\r\n * entry logged on the same tick as construction — e.g. at app boot, before\r\n * the base schedules `init()` on the next tick via `setTimeout(0)` — is not\r\n * silently dropped. The `options` (lazy-import) path is inherently async and\r\n * still resolves in `init()`.\r\n */\r\n public constructor(configurations?: SentryLogConfig) {\r\n super(configurations);\r\n\r\n const injected = this.config(\"client\");\r\n\r\n if (injected) {\r\n this.sentry = injected;\r\n }\r\n }\r\n\r\n /**\r\n * Resolve the forwarder: reuse the injected client, otherwise lazily import\r\n * `@sentry/node` and (only when explicit `options` are supplied and no client\r\n * exists yet) initialize it. Never throws — the base runs `init()` inside an\r\n * un-awaited `setTimeout`, so a throw would become an unhandled rejection and\r\n * `isInitialized` would never flip; a missing SDK is reported from `log()`.\r\n */\r\n protected async init(): Promise<void> {\r\n const injected = this.config(\"client\");\r\n\r\n if (injected) {\r\n this.sentry = injected;\r\n\r\n return;\r\n }\r\n\r\n await loadSentry();\r\n\r\n if (!Sentry) {\r\n return;\r\n }\r\n\r\n const options = this.config(\"options\");\r\n\r\n if (options && !Sentry.getClient()) {\r\n Sentry.init(options);\r\n }\r\n\r\n this.sentry = Sentry;\r\n }\r\n\r\n /**\r\n * {@inheritdoc}\r\n */\r\n public async log(data: LoggingData): Promise<void> {\r\n if (!this.shouldBeLogged(data)) {\r\n return;\r\n }\r\n\r\n if (isModuleExists === null) {\r\n // wait until module is fully loaded\r\n await loadSentry();\r\n }\r\n\r\n if (!this.sentry) {\r\n this.reportMissingSdk();\r\n\r\n return;\r\n }\r\n\r\n const { module, action, message, type: level, context } = data;\r\n\r\n if (this.isEventLevel(level)) {\r\n this.captureEvent(this.sentry, {\r\n module,\r\n action,\r\n message,\r\n level,\r\n context,\r\n });\r\n\r\n return;\r\n }\r\n\r\n this.sentry.addBreadcrumb({\r\n category: module,\r\n message: this.toText(message),\r\n level: this.toSentryLevel(level),\r\n data: context,\r\n });\r\n }\r\n\r\n /**\r\n * Drain pending Sentry events. Bounded by `flushTimeout` so an unreachable\r\n * Sentry can never hang a graceful shutdown. No-op when the SDK is absent.\r\n */\r\n public async flush(): Promise<void> {\r\n if (!this.sentry) {\r\n return;\r\n }\r\n\r\n await this.sentry.flush(this.config(\"flushTimeout\"));\r\n }\r\n\r\n /**\r\n * Whether the level should be sent as a Sentry event (vs a breadcrumb).\r\n */\r\n private isEventLevel(level: LogLevel): boolean {\r\n return Boolean(this.config(\"eventLevels\")?.includes(level));\r\n }\r\n\r\n /**\r\n * Send an entry as a Sentry event. An `Error` message goes through\r\n * `captureException` so Sentry parses the real stack and groups properly;\r\n * any other message goes through `captureMessage`. `module` / `action` are\r\n * attached as tags and `context` as a structured context, scoped to this\r\n * event only via `withScope`.\r\n */\r\n private captureEvent(\r\n sentry: SentryForwarder,\r\n entry: {\r\n module: string;\r\n action: string;\r\n message: unknown;\r\n level: LogLevel;\r\n context?: Record<string, any>;\r\n },\r\n ): void {\r\n const { module, action, message, level, context } = entry;\r\n const sentryLevel = this.toSentryLevel(level);\r\n\r\n sentry.withScope((scope) => {\r\n scope.setLevel(sentryLevel);\r\n scope.setTags({ module, action });\r\n\r\n if (context) {\r\n scope.setContext(\"context\", context);\r\n }\r\n\r\n if (message instanceof Error) {\r\n sentry.captureException(message);\r\n } else {\r\n sentry.captureMessage(this.toText(message), sentryLevel);\r\n }\r\n });\r\n }\r\n\r\n /**\r\n * Map a logger level to a Sentry severity. `success` has no Sentry\r\n * equivalent, so it is reported as informational.\r\n */\r\n private toSentryLevel(level: LogLevel): SentrySeverityLevel {\r\n switch (level) {\r\n case \"warn\":\r\n return \"warning\";\r\n case \"success\":\r\n return \"info\";\r\n default:\r\n return level; // debug | info | error | fatal map 1:1\r\n }\r\n }\r\n\r\n /**\r\n * Coerce a message into the string Sentry's APIs expect — an `Error`'s\r\n * `.message`, a string as-is, anything else safely JSON-serialized.\r\n */\r\n private toText(message: unknown): string {\r\n if (typeof message === \"string\") {\r\n return message;\r\n }\r\n\r\n if (message instanceof Error) {\r\n return message.message;\r\n }\r\n\r\n return safeJsonStringify(message);\r\n }\r\n\r\n /**\r\n * Surface the install instructions exactly once when the SDK is absent. The\r\n * logger can't log through itself here, so this writes to stderr — matching\r\n * how the file channels report write failures.\r\n */\r\n private reportMissingSdk(): void {\r\n if (isModuleExists === false && !this.warnedMissing) {\r\n this.warnedMissing = true;\r\n console.error(SENTRY_INSTALL_INSTRUCTIONS);\r\n }\r\n }\r\n}\r\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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,KAAK,QACR;EAGF,MAAM,KAAK,OAAO,MAAM,KAAK,OAAO,cAAc,CAAC;CACrD;;;;CAKA,AAAQ,aAAa,OAA0B;EAC7C,OAAO,QAAQ,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"}
|
package/esm/index.d.mts
CHANGED
|
@@ -3,9 +3,10 @@ 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
|
+
import { SentryBreadcrumb, SentryForwarder, SentryInitOptions, SentryLog, SentryLogConfig, SentryScopeLike } from "./channels/sentry-log.mjs";
|
|
6
7
|
import { Logger, log } from "./logger.mjs";
|
|
7
8
|
import { applyRedact, mergeRedact } from "./redact/redact.mjs";
|
|
8
9
|
import { captureAnyUnhandledRejection } from "./utils/capture-unhandled-errors.mjs";
|
|
9
10
|
import { clearMessage } from "./utils/clear-message.mjs";
|
|
10
11
|
import { safeJsonStringify } from "./utils/safe-json-stringify.mjs";
|
|
11
|
-
export { AutoFlushEvent, BasicLogConfigurations, ConsoleLog, ConsoleLogConfig, DebugMode, FileLog, FileLogConfig, JSONFileLog, LogChannel, LogContract, LogLevel, LogMessage, Logger, LoggingData, OmittedLoggingData, RedactCensor, RedactConfig, applyRedact, captureAnyUnhandledRejection, clearMessage, log, mergeRedact, safeJsonStringify };
|
|
12
|
+
export { AutoFlushEvent, BasicLogConfigurations, ConsoleLog, ConsoleLogConfig, DebugMode, FileLog, FileLogConfig, JSONFileLog, LogChannel, LogContract, LogLevel, LogMessage, Logger, LoggingData, OmittedLoggingData, RedactCensor, RedactConfig, SentryBreadcrumb, SentryForwarder, SentryInitOptions, SentryLog, SentryLogConfig, SentryScopeLike, applyRedact, captureAnyUnhandledRejection, clearMessage, log, mergeRedact, safeJsonStringify };
|
package/esm/index.mjs
CHANGED
|
@@ -3,6 +3,7 @@ import { ConsoleLog } from "./channels/console-log.mjs";
|
|
|
3
3
|
import { FileLog } from "./channels/file-log.mjs";
|
|
4
4
|
import { safeJsonStringify } from "./utils/safe-json-stringify.mjs";
|
|
5
5
|
import { JSONFileLog } from "./channels/json-file-log.mjs";
|
|
6
|
+
import { SentryLog } from "./channels/sentry-log.mjs";
|
|
6
7
|
import "./channels/index.mjs";
|
|
7
8
|
import { applyRedact, mergeRedact } from "./redact/redact.mjs";
|
|
8
9
|
import { clearMessage } from "./utils/clear-message.mjs";
|
|
@@ -10,4 +11,4 @@ import { Logger, log } from "./logger.mjs";
|
|
|
10
11
|
import { captureAnyUnhandledRejection } from "./utils/capture-unhandled-errors.mjs";
|
|
11
12
|
import "./utils/index.mjs";
|
|
12
13
|
|
|
13
|
-
export { ConsoleLog, FileLog, JSONFileLog, LogChannel, Logger, applyRedact, captureAnyUnhandledRejection, clearMessage, log, mergeRedact, safeJsonStringify };
|
|
14
|
+
export { ConsoleLog, FileLog, JSONFileLog, LogChannel, Logger, SentryLog, applyRedact, captureAnyUnhandledRejection, clearMessage, log, mergeRedact, 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 ../@warlock.js/logger/src/log-channel.d.ts
|
|
4
4
|
declare abstract class LogChannel<Options extends BasicLogConfigurations = BasicLogConfigurations> implements LogContract {
|
|
5
5
|
/**
|
|
6
6
|
* Channel name
|
|
@@ -54,6 +54,14 @@ declare abstract class LogChannel<Options extends BasicLogConfigurations = Basic
|
|
|
54
54
|
* Synchronously flush messages
|
|
55
55
|
*/
|
|
56
56
|
flushSync?(): void;
|
|
57
|
+
/**
|
|
58
|
+
* Asynchronously flush buffered messages.
|
|
59
|
+
*
|
|
60
|
+
* Optional — channels that write synchronously per entry (e.g. `ConsoleLog`)
|
|
61
|
+
* don't implement it. Buffering channels override this to drain their buffer
|
|
62
|
+
* over async I/O so callers can `await log.flush()` on graceful shutdown.
|
|
63
|
+
*/
|
|
64
|
+
flush?(): void | Promise<void>;
|
|
57
65
|
/**
|
|
58
66
|
* Read the channel's redact config (if any). Used by `Logger` to apply
|
|
59
67
|
* per-channel additive redaction on top of the logger-wide floor.
|