Skip to content

Instantly share code, notes, and snippets.

@darkcolonist
Created June 1, 2017 08:42
Show Gist options
  • Save darkcolonist/7dcbcbcaa0b59f9ee4bcb140711cd58e to your computer and use it in GitHub Desktop.
Save darkcolonist/7dcbcbcaa0b59f9ee4bcb140711cd58e to your computer and use it in GitHub Desktop.
winston logging to separate files
var winston = require('winston');
var moment = require('moment-timezone');
util = {
/**
* get a moment instance pre-configured
* @param string datetime nullable
* @param Object customParams
* {
* // null if you prefer application timezone
* timezone: "America/Los_Angeles",
*
* // null if you prefer the default format of momentJS
* format: "MMMM Do YYYY, h:mm:ss a",
* }
* @return {[type]} [description]
*/
moment: function(datetime, customParams){
if(datetime === null)
datetime = undefined;
var myMoment = moment(datetime);
if(customParams === undefined)
customParams = {};
if(customParams.timezone !== undefined){
myMoment.tz(customParams.timezone);
}else{
myMoment.tz(config.app.timezone);
}
if(customParams.format !== undefined){
return myMoment.format(customParams.format);
}else{
return myMoment;
}
},
/**
* like the above but instead, this logs to file
*
* sample usage:
*
* util.logf('debug-leakance','example-'+util.randstring(4, util.rand(5,16)));
* util.logf('debug-duodecimo','example-'+util.randstring(4, util.rand(5,16)));
* util.logf('debug-undefied','example-'+util.randstring(4, util.rand(5,16)));
* util.logf('debug-burring','example-'+util.randstring(4, util.rand(5,16)));
* util.logf('debug-lux','example-'+util.randstring(4, util.rand(5,16)));
*/
logf: function(type, message, level){
var level = level === undefined ? "info" : level;
var theLogger = null;
if(util._loggers[type] == undefined){
theLogger = new (winston.Logger)({
transports: [
new (winston.transports.File)({
filename: `./traces/${type}.log`,
json: false,
maxsize: 1000000, // 1MB
timestamp: () => {
return util.moment(null, {
// format: "YYYY-MM-DD HH:mm:ss.SS",
format: "YYYY-MMM-DD h:mm:ss.SSA",
timezone: "Asia/Manila"
});
},
maxFiles: 1
})
]
});
util._loggers[type] = theLogger;
}else{
theLogger = util._loggers[type];
}
theLogger.log(level, message);
}
};
@darkcolonist
Copy link
Author

image

@darkcolonist
Copy link
Author

image

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