Skip to content

Instantly share code, notes, and snippets.

@andresmatasuarez
Last active August 29, 2015 14:16
Show Gist options
  • Save andresmatasuarez/66edcd9710986cca4c59 to your computer and use it in GitHub Desktop.
Save andresmatasuarez/66edcd9710986cca4c59 to your computer and use it in GitHub Desktop.
NodeJS | Module: Log | Logging utils.
/**
* @module Log
* @desc Logging utils.
* @see {@link https://gist.github.com/andresmatasuarez/66edcd9710986cca4c59| GitHub gist}
* @author Andrés Mata Suárez <amatasuarez@gmail>
* @license {@link http://www.opensource.org/licenses/mit-license.php| MIT License}
*
* @requires {@link http://nodejs.org/api/util.html| util}
* @requires {@link https://github.com/lorenwest/node-config| config}
* @requires {@link https://github.com/winstonjs/winston| winston}
*
* @example
* var Log = require('./log');
*
* Log.blankLine();
*
* Log.context('Custom context').info('Custom operation')();
* Log.context('Custom context').error('Custom error')();
*
*/
'use strict';
var util = require('util');
var config = require('config');
var winston = require('winston');
var largestContextLength = 0;
var logger = new winston.Logger({
transports: [
new winston.transports.Console({ silent: config.logs && config.logs.silent })
]
});
function _padding(context){
var spacesToFill = largestContextLength - context.length;
return (spacesToFill !== 0 ? ' ' : '') + new Array(spacesToFill).join(' ');
}
function _log(type){
return function(context, msg){
return function(){
var args = Array.prototype.slice.call(arguments);
args.unshift(context + _padding(context) + ' | ' + msg);
logger.log(type, util.format.apply(util, args));
};
};
}
function _context(context){
context = context || '';
largestContextLength = largestContextLength < context.length ? context.length : largestContextLength;
return {
info: function(msg){
return _log('info')(context, msg);
},
error: function(msg){
return _log('error')(context, msg);
}
};
}
module.exports = {
context: _context,
blankLine: _context().info(''),
Repeat: {
start : _context('Repeat').info('Started task: %s.'),
repeat : _context('Repeat').info('Repeating task: %s...'),
waiting : _context('Repeat').info('Waiting %s millis before repeating task: %s.'),
stop : _context('Repeat').info('Stopped task: %s.'),
alreadyStarted : _context('Repeat').info('Task already started: %s.'),
alreadyStopped : _context('Repeat').info('Task already stopped: %s.'),
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment