From c22c48ddede7ade6330225915c19062d9c01a6ed Mon Sep 17 00:00:00 2001 From: alexander Date: Wed, 30 Dec 2020 17:16:42 -0500 Subject: [PATCH] Fix defaultMeta override in child logger #1864 --- lib/winston/logger.js | 18 +++++++++++++++++- test/logger.test.js | 6 +++++- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/lib/winston/logger.js b/lib/winston/logger.js index dc7866854..27d357384 100644 --- a/lib/winston/logger.js +++ b/lib/winston/logger.js @@ -44,13 +44,29 @@ class Logger extends Transform { child(defaultRequestMetadata) { const logger = this; + return Object.create(logger, { write: { value: function (info) { + + // Remark: defaultMeta is passed into the info object, + // and we need to check if it is there because a user + // specified it in a log call or it is there as a result + // of being passed to createLogger as defaultMeta. + const defaultMetaOverride = {}; + if (logger.defaultMeta) { + for (const key of Object.getOwnPropertyNames(logger.defaultMeta)) { + if (info[key] === logger.defaultMeta[key]) { + defaultMetaOverride[key] = defaultRequestMetadata[key]; + } + } + } + const infoClone = Object.assign( {}, defaultRequestMetadata, - info + info, + defaultMetaOverride ); // Object.assign doesn't copy inherited Error diff --git a/test/logger.test.js b/test/logger.test.js index 0d21d3fa1..4d154d813 100755 --- a/test/logger.test.js +++ b/test/logger.test.js @@ -997,12 +997,16 @@ describe('Should support child loggers & defaultMeta', () => { }); const logger = winston.createLogger({ + defaultMeta: { + requestId: '38', + service: 'root-service-logger' + }, transports: [ mockTransport.createMockTransport(assertFn) ] }); - const childLogger = logger.child({ service: 'user-service' }); + const childLogger = logger.child({ service: 'user-service', requestId: '154' }); childLogger.info('dummy message', { requestId: '451' }); });