Skip to content

Commit

Permalink
[fix refactor] Correctly interpret intent around string interpolation…
Browse files Browse the repository at this point in the history
… or "meta" objects based on the occurance of the format expressions in the base message to be logged.
  • Loading branch information
indexzero committed Oct 29, 2015
1 parent 3747ccf commit 163f4f9
Showing 1 changed file with 20 additions and 3 deletions.
23 changes: 20 additions & 3 deletions lib/winston/logger.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ var events = require('events'),
exception = require('./exception'),
Stream = require('stream').Stream;

const formatRegExp = /%[sdj%]/g;

//
// ### function Logger (options)
// #### @options {Object} Options for this instance.
Expand Down Expand Up @@ -118,9 +120,9 @@ Logger.prototype.log = function (level) {
//
// logger.info('No interpolation symbols', 'ok', 'why', { meta: 'is-this' });
//
var callback = typeof args[args.length - 1] === 'function' ? args.pop() : null,
meta = typeof args[args.length - 1] === 'object' && Object.prototype.toString.call(args[args.length - 1]) !== '[object RegExp]' ? args.pop() : {},
msg = util.format.apply(null, args);
var callback = typeof args[args.length - 1] === 'function'
? args.pop()
: null;

//
// Handle errors appropriately.
Expand Down Expand Up @@ -157,6 +159,21 @@ Logger.prototype.log = function (level) {
return;
}

//
// Determining what is `meta` and what are arguments for string interpolation
// turns out to be VERY tricky. e.g. in the cases like this:
//
// logger.info('No interpolation symbols', 'ok', 'why', { meta: 'is-this' });
//
var metaType = Object.prototype.toString.call(args[args.length - 1]),
fmtMatch = args[0].match && args[0].match(formatRegExp),
isFormat = fmtMatch && fmtMatch.length,
validMeta = !isFormat
? metaType === '[object Object]' || metaType === '[object Error]' || metaType === '[object Array]'
: metaType === '[object Object]',
meta = validMeta ? args.pop() : {},
msg = util.format.apply(null, args);

//
// Respond to the callback.
//
Expand Down

0 comments on commit 163f4f9

Please sign in to comment.