Skip to content

Instantly share code, notes, and snippets.

@craiggoldstone
Created April 11, 2013 23:38
Show Gist options
  • Save craiggoldstone/5368096 to your computer and use it in GitHub Desktop.
Save craiggoldstone/5368096 to your computer and use it in GitHub Desktop.
Async logging in Node.JS – JUST CHILL, WINSTON.
var winston = require('winston');
var fs = require('fs');
fs.mkdir('./logs', function(err) {
if (err) throw err;
});
// Define levels to be like log4j in java
var customLevels = {
levels: {
debug: 0,
info: 1,
warn: 2,
error: 3
},
colors: {
debug: 'blue',
info: 'green',
warn: 'yellow',
error: 'red'
}
};
// create the main logger
var logger = new(winston.Logger)({
level: 'debug',
levels: customLevels.levels,
transports: [
// setup console logging
new(winston.transports.Console)({
level: 'info', // Only write logs of info level or higher
levels: customLevels.levels,
colorize: true
}),
// setup logging to file
new(winston.transports.File)({
filename: './logs/project-debug.log',
maxsize: 1024 * 1024 * 10, // 10MB
level: 'debug',
levels: customLevels.levels
})
]
});
// create the data logger - I only log specific app output data here
var datalogger = new (winston.Logger) ({
level: 'info',
transports: [
new (winston.transports.File) ({
filename: './logs/project-data.log',
maxsize: 1024 * 1024 * 10 // 10MB
})
]
});
// make winston aware of your awesome colour choices
winston.addColors(customLevels.colors);
var Logging = function() {
var loggers = {};
// always return the singleton instance, if it has been initialised once already.
if (Logging.prototype._singletonInstance) {
return Logging.prototype._singletonInstance;
}
this.getLogger = function(name) {
return loggers[name];
}
this.get = this.getLogger;
loggers['project-debug.log'] = logger;
loggers['project-data.log'] = datalogger;
Logging.prototype._singletonInstance = this;
};
new Logging(); // I decided to force instantiation of the singleton logger here
logger.info('Logging set up OK!');
exports.Logging = Logging;
@markthien
Copy link

Please change to (at line 4):

if(!fs.existsSync(dirLog)) {

fs.mkdir(dirLog, function(err) {

    if (err) throw err;

});

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment