Skip to content

Instantly share code, notes, and snippets.

@nigilan
Created November 3, 2017 11:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nigilan/f18cd70d967a8a55e90f7db442e8b4b9 to your computer and use it in GitHub Desktop.
Save nigilan/f18cd70d967a8a55e90f7db442e8b4b9 to your computer and use it in GitHub Desktop.
Winston logger and daily rotator
/**
* Configurations of logger.
*/
const winston = require('winston');
process.env.NODE_ENV = "production";
const env = process.env.NODE_ENV;
const fs = require('fs');
var util = require('util');
const logDir = 'applicationlog';
// Create the log directory if it does not exist
if (!fs.existsSync(logDir)) {
fs.mkdirSync(logDir);
}
const successLogger = new (winston.Logger)({
transports: [
// colorize the output to the console
new (winston.transports.Console)({
colorize: true,
level: "info"
}),
new (require('winston-daily-rotate-file'))({
filename: `${logDir}/-results.log`,
datePattern: 'dd-MM-yyyy',
prepend: true,
level: "info",
timestamp : function() {
return getDateTime();
}
})
]
});
const errorLogger = new (winston.Logger)({
transports: [
// colorize the output to the console
new (winston.transports.Console)({
colorize: true,
level: "error"
}),
new (require('winston-daily-rotate-file'))({
filename: `${logDir}/-error.log`,
datePattern: 'dd-MM-yyyy',
prepend: true,
level: "error",
timestamp : function() {
return getDateTime();
}
})
]
});
if (env === "production") {
errorLogger.remove(winston.transports.Console);
successLogger.remove(winston.transports.Console);
}
function getDateTime(){
var currentdate = new Date();
var datetime = currentdate.getDate() + "/"
+ (currentdate.getMonth()+1) + "/"
+ currentdate.getFullYear() + " "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
return datetime;
}
function formatArgs(args){
return [util.format.apply(util.format, Array.prototype.slice.call(args))];
}
console.log = function(){
successLogger.info.apply(successLogger, formatArgs(arguments));
};
console.error = function(){
errorLogger.error.apply(errorLogger, formatArgs(arguments));
};
module.exports = {
'successlog': successLogger,
'errorlog': errorLogger
};
@sradhaa
Copy link

sradhaa commented Dec 19, 2018

Its showing TypeError: winston.Logger is not a constructor
How can I fix this one ?
Is there any version problem , current version is 3.0?

@olegs18
Copy link

olegs18 commented Aug 25, 2019

Its showing TypeError: winston.Logger is not a constructor
How can I fix this one ?
Is there any version problem , current version is 3.0?

Replace new (winston.Logger) on winston.createLogger

@shaheemMPM
Copy link

timestamp is not showing in this logger
can you edit that?

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