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

push/pop() context #6

Closed
wants to merge 9 commits 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
4 changes: 2 additions & 2 deletions lib/winston.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ winston.Logger = require('winston/logger').Logger;
var defaultLogger = new (winston.Logger)({ transports: [new (winston.transports.Console)()] });
utils.setLevels(winston, null, defaultLogger.levels);

['log', 'add', 'remove', 'profile', 'extend'].forEach(function (method) {
['log', 'add', 'remove', 'profile', 'extend', 'withContext', 'push', 'pop'].forEach(function (method) {
winston[method] = function () {
return defaultLogger[method].apply(defaultLogger, arguments);
};
Expand Down Expand Up @@ -89,4 +89,4 @@ Object.defineProperty(winston, 'padLevels', {
//
winston.defaultTransports = function () {
return defaultLogger.transports;
};
};
66 changes: 64 additions & 2 deletions lib/winston/logger.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,16 @@ var Logger = exports.Logger = function (options) {

var self = this;
options = options || {};
this.options = options;

// Set Levels and default logging level
this.padLevels = options.padLevels || false;
this.setLevels(options.levels);
this.level = options.level || 'info';

// Set default context state and separator
this.context = [];
this.contextSeparator = options.contextSeparator || '::';

this.emitErrs = options.emitErrs || false;
this.transports = {};
Expand All @@ -45,7 +50,7 @@ var Logger = exports.Logger = function (options) {
options.transports.forEach(function (transport) {
self.transports[transport.name] = transport;
});
}
}
};

util.inherits(Logger, events.EventEmitter);
Expand All @@ -64,6 +69,58 @@ Logger.prototype.extend = function (target) {
});
};


//
// function withContext (context)
// Returns copy of curent logger with isolated context. So push() will not
// affect original logger.
//
Logger.prototype.withContext = function (context) {
var that = this, logger = {}, prop, descriptor;

// clone all prperties
Object.getOwnPropertyNames(this).forEach(function(prop) {
descriptor = Object.getOwnPropertyDescriptor(that, prop);
Object.defineProperty(logger, prop, descriptor)
});

logger.__original__ = this;
logger.__proto__ = this.__proto__;
logger.context = [].concat(this.context);

// re-assign level methods
utils.setLevels(logger, this.levels, this.levels);

return context ? logger.push(context) : logger;
};

//
// function push (context)
// Appends new context to the stack.
//
Logger.prototype.push = function (context) {
this.context.push(String(context));
return this;
};

//
// function pop ([amount = 1])
// Removes last `amount` of contexts from the stack.
// Pops out all contexts if `amount` < 0.
//
// - `logger.pop()` as well as `logger.pop(0)` equals to `logger.pop(1)`
// - `logger.pop(-1)` equals to `logger.pop().pop().pop()`,
// when logger had three contexts registered
//
Logger.prototype.pop = function (amount) {
amount = Number(amount || 1);
while (0 < this.context.length && 0 != amount) {
this.context.pop();
amount--;
}
return this;
};

//
// function log (level, msg, [meta, callback])
// Core logging method for Winston. Metadata and callback are is optional.
Expand All @@ -87,6 +144,11 @@ Logger.prototype.log = function (level, msg) {
callback = arguments[3];
}

// If we have context add it
if (this.context.length) {
msg = '[' + this.context.join(this.contextSeparator) + '] ' + msg;
}

// If we should pad for levels, do so
if (this.padLevels) {
msg = new Array(this.levelLength - level.length).join(' ') + msg;
Expand Down Expand Up @@ -176,4 +238,4 @@ Logger.prototype.profile = function (id) {

Logger.prototype.setLevels = function (current) {
return utils.setLevels(this, this.levels, current);
};
};
36 changes: 35 additions & 1 deletion test/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -105,4 +105,38 @@ helpers.testLevels = function (levels, transport, assertMsg, assertFn) {
test[assertMsg] = assertFn;
tests['when passed metadata'] = test;
return tests;
};
};

helpers.testWithContext = function (logger) {
return {
topic: function() {
return logger.withContext('clone');
},
"it should create a copy of the logger": function (clone) {
assert.isObject(clone);
assert.isObject(clone.__original__);
assert.notEqual(clone, clone.__original__);
},
"and push provided context to the copy instance only": function (clone) {
assert.length(clone.__original__.context, 0);
assert.length(clone.context, 1);
},
"calling level methods, e.g. info(),": {
topic: function (clone) {
clone.info('test message', this.callback);
},
"will use right log() method": function (err, lvl, msg) {
assert.match(msg, /^\[clone\]/);
}
},
"calling push() method": {
topic: function (clone) {
return clone.push('clone');
},
"should push new context to the stack of clone": function (clone) {
assert.length(clone.__original__.context, 0);
assert.length(clone.context, 2);
}
}
};
};
60 changes: 59 additions & 1 deletion test/logger-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,64 @@ vows.describe('winton/logger').addBatch({
}
}
}
}).addBatch({
"winston.Logger#withContext": helpers.testWithContext(
new (winston.Logger)({
transports: [
new (winston.transports.Console)()
]
})
)
}).addBatch({
"winston defaultLogger": {
topic: winston,
"should response to withContext, push and pop methods": function (logger) {
assert.isFunction(logger.withContext);
assert.isFunction(logger.push);
assert.isFunction(logger.pop);
},
"deals withContext, just as normal logger, so": helpers.testWithContext(winston)
}
}).addBatch({
"When winston.Logger with transports": {
topic: new (winston.Logger)({
transports: [
new (winston.transports.Console)(),
]
}),
"calls push() method": {
topic: function (logger) {
return logger.push('con').push('t').push('ext');
},
"it should add specified context to the stack": function (logger) {
assert.length(logger.context, 3);
},
"and then calls log() method": {
topic: function (logger) {
logger.log('info', 'test message', this.callback);
},
"message should be prefixed with specified context": function (err, lvl, msg) {
assert.match(msg, /^\[con::t::ext\]/);
}
},
"and then calls pop() method": {
topic: function (logger) {
return logger.pop();
},
"should pop one last context out": function (logger) {
assert.length(logger.context, 2);
},
"until there no more contexts left, calling log() method": {
topic: function (logger) {
logger.pop(-1).log('info', 'test message', this.callback);
},
"should log message without any prefix": function (err, lvl, msg) {
assert.equal(msg, 'test message');
}
}
}
}
}
}).addBatch({
"The winston logger": {
topic: new (winston.Logger)({
Expand Down Expand Up @@ -146,4 +204,4 @@ vows.describe('winton/logger').addBatch({
}
}
}
}).export(module);
}).export(module);