Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@sradhaa 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

This comment has been minimized.

Copy link

@olegs18 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

This comment has been minimized.

Copy link

@shaheemMPM shaheemMPM commented Feb 3, 2021

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