Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix defaultMeta override in child logger #1864 #1875

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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