Skip to content

Commit

Permalink
Fix defaultMeta override in child logger winstonjs#1864
Browse files Browse the repository at this point in the history
  • Loading branch information
aressler38 committed Dec 30, 2020
1 parent 2625f60 commit c22c48d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
18 changes: 17 additions & 1 deletion lib/winston/logger.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 5 additions & 1 deletion test/logger.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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' });
});

Expand Down

0 comments on commit c22c48d

Please sign in to comment.