Skip to content

Commit 9c2e2a9

Browse files
committed
lib: optimize logger by checking hasSubscribers early
1 parent ad2a56a commit 9c2e2a9

File tree

2 files changed

+17
-8
lines changed

2 files changed

+17
-8
lines changed

benchmark/logger/vs-pino.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -143,4 +143,4 @@ function main({ n, logger, scenario }) {
143143

144144
destination.flushSync();
145145
}
146-
}
146+
}

lib/logger.js

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ const {
2424

2525
const Utf8Stream = require('internal/streams/fast-utf8-stream');
2626
const diagnosticsChannel = require('diagnostics_channel');
27+
const { kEmptyObject } = require('internal/util');
2728

2829
// Create channels for each log level
2930
const channels = {
@@ -282,6 +283,20 @@ class Logger {
282283
return;
283284
}
284285

286+
if (typeof msgOrObj === 'string') {
287+
if (fields !== undefined) {
288+
validateObject(fields, 'fields');
289+
}
290+
} else if (!this._isError(msgOrObj)) {
291+
validateObject(msgOrObj, 'obj');
292+
validateString(msgOrObj.msg, 'obj.msg');
293+
}
294+
295+
const channel = channels[level];
296+
if (!channel.hasSubscribers) {
297+
return;
298+
}
299+
285300
let msg;
286301
let logFields;
287302

@@ -294,10 +309,7 @@ class Logger {
294309
} else if (typeof msgOrObj === 'string') {
295310
msg = msgOrObj;
296311
logFields = fields || kEmptyObject;
297-
validateObject(logFields, 'fields');
298312
} else {
299-
validateObject(msgOrObj, 'obj');
300-
validateString(msgOrObj.msg, 'obj.msg');
301313
const { msg: extractedMsg, ...restFields } = msgOrObj;
302314
msg = extractedMsg;
303315
logFields = restFields;
@@ -315,10 +327,7 @@ class Logger {
315327
fields: logFields,
316328
};
317329

318-
const channel = channels[level];
319-
if (channel.hasSubscribers) {
320-
channel.publish(record);
321-
}
330+
channel.publish(record);
322331
}
323332

324333
/**

0 commit comments

Comments
 (0)