From 751bd73175ef39f63fcf5b90a936f47e1a45ce9a Mon Sep 17 00:00:00 2001 From: YANG QIA <2013xile@gmail.com> Date: Wed, 20 Mar 2024 09:50:04 +0800 Subject: [PATCH] fix(logger): output error cause info (#3760) * fix(logger): output error cause info * fix: typo --- packages/core/logger/src/system-logger.ts | 48 +++++++++++++++++++++-- 1 file changed, 44 insertions(+), 4 deletions(-) diff --git a/packages/core/logger/src/system-logger.ts b/packages/core/logger/src/system-logger.ts index 76ed33d2f..03ba4d7f4 100644 --- a/packages/core/logger/src/system-logger.ts +++ b/packages/core/logger/src/system-logger.ts @@ -49,13 +49,13 @@ class SystemLoggerTransport extends Transport { } log(info: any, callback: any) { - const { level, message, reqId, app, stack, [SPLAT]: args } = info; + const { level, message, reqId, app, stack, cause, [SPLAT]: args } = info; const logger = level === 'error' && this.errorLogger ? this.errorLogger : this.logger; const { module, submodule, method, ...meta } = args?.[0] || {}; logger.log({ level, - stack, message, + stack, meta, module: module || info['module'] || '', submodule: submodule || info['submodule'] || '', @@ -63,11 +63,51 @@ class SystemLoggerTransport extends Transport { app, reqId, }); + if (cause) { + logger.log({ + level, + message: cause.message, + stack: cause.stack, + app, + reqId, + }); + } callback(null, true); } } -export const createSystemLogger = (options: SystemLoggerOptions): SystemLogger => - winston.createLogger({ +function child(defaultRequestMetadata: any) { + const logger = this; + return Object.create(logger, { + write: { + value: function (info: any) { + const infoClone = Object.assign({}, defaultRequestMetadata, info); + + if (info instanceof Error) { + infoClone.stack = info.stack; + infoClone.message = info.message; + infoClone.cause = info.cause; + } + + logger.write(infoClone); + }, + }, + }); +} + +export const createSystemLogger = (options: SystemLoggerOptions): SystemLogger => { + const logger = winston.createLogger({ transports: [new SystemLoggerTransport(options)], }); + + // Since error.cause is not supported by child logger of winston + // we have to use a proxy to rewrite child method + return new Proxy(logger, { + get(target, prop) { + if (prop === 'child') { + return child.bind(target); + } + return Reflect.get(target, prop); + }, + }); +};