diff --git a/packages/logger/src/Logger.ts b/packages/logger/src/Logger.ts index 3a8859e447..85ab7f2428 100644 --- a/packages/logger/src/Logger.ts +++ b/packages/logger/src/Logger.ts @@ -25,6 +25,7 @@ import type { LogItemMessage, LoggerInterface, PowertoolsLogData, + OutputFormatter, } from './types/Logger.js'; /** @@ -162,6 +163,10 @@ class Logger extends Utility implements LoggerInterface { private powertoolsLogData: PowertoolsLogData = {}; + private outputFormatter: OutputFormatter = (str: string): string => { + return str; + }; + /** * Log level used by the current instance of Logger. * @@ -798,13 +803,21 @@ class Logger extends Utility implements LoggerInterface { 'critical' >); - this.console[consoleMethod]( - JSON.stringify( - log.getAttributes(), - this.getReplacer(), - this.logIndentation - ) + let result = JSON.stringify( + log.getAttributes(), + this.getReplacer(), + this.logIndentation ); + + const formatted = this.outputFormatter(result); + try { + JSON.parse(formatted); + result = formatted; + } catch (e) { + // console.warn('Incorrect formatted JSON. Use original data.'); + } + + this.console[consoleMethod](result); } /** @@ -999,6 +1012,7 @@ class Logger extends Utility implements LoggerInterface { customConfigService, persistentLogAttributes, environment, + outputFormatter, } = options; // order is important, EnvVarsService() is used by other methods @@ -1012,6 +1026,7 @@ class Logger extends Utility implements LoggerInterface { this.setLogEvent(); this.setLogIndentation(); this.addPersistentLogAttributes(persistentLogAttributes); + this.setOutputFormatter(outputFormatter); return this; } @@ -1044,6 +1059,12 @@ class Logger extends Utility implements LoggerInterface { }); this.addPersistentLogAttributes(persistentLogAttributes); } + + private setOutputFormatter(formatter?: OutputFormatter): void { + if (formatter) { + this.outputFormatter = formatter; + } + } } export { Logger }; diff --git a/packages/logger/src/types/Logger.ts b/packages/logger/src/types/Logger.ts index fdeb41d4e3..12334e1c08 100644 --- a/packages/logger/src/types/Logger.ts +++ b/packages/logger/src/types/Logger.ts @@ -21,6 +21,8 @@ type InjectLambdaContextOptions = { clearState?: boolean; }; +type OutputFormatter = (jsonString: string) => string; + type ConstructorOptions = { logLevel?: LogLevel; serviceName?: string; @@ -29,6 +31,7 @@ type ConstructorOptions = { customConfigService?: ConfigServiceInterface; persistentLogAttributes?: LogAttributes; environment?: Environment; + outputFormatter?: OutputFormatter; }; type LambdaFunctionContext = Pick< @@ -96,4 +99,5 @@ export type { PowertoolsLogData, ConstructorOptions, InjectLambdaContextOptions, + OutputFormatter, };