Skip to content

Instantly share code, notes, and snippets.

@JonFranklin301
Created March 2, 2019 21:40
Show Gist options
  • Save JonFranklin301/7688c2be4dc04b4a787c9aca218b32ff to your computer and use it in GitHub Desktop.
Save JonFranklin301/7688c2be4dc04b4a787c9aca218b32ff to your computer and use it in GitHub Desktop.
Winston logging with formatting
const { format, createLogger, transports } = require('winston');
const moment = require('moment');
// Thanks to luislobo for the workaround to handle multiple parameters - https://github.com/winstonjs/winston/issues/1427#issuecomment-427104223
// Format Object
function formatObject(param) {
if (param instanceof Object) {
return JSON.stringify(param);
}
return param;
}
// Format splat into message string
const all = format(info => {
const splat = info[Symbol.for('splat')] || [];
const message = formatObject(info.message);
const rest = splat.map(formatObject).join(' ');
info.message = `${message} ${rest}`;
return info;
});
// Define the settings for each transport
var options = {
jsonFile: {
level: 'info',
name: 'file.json.info',
filename: `./logs/${moment().format('YYYY-MM-DD')}-info.log`,
handleExceptions: true,
json: true,
maxsize: 5242880, // 5MB
maxFiles: 100,
format: format.combine(
all(),
format.timestamp(),
format.printf(info => {
return `{"timestamp":"${info.timestamp}","level":"${info.level}","message":"${formatObject(info.message)}"}`;
})
)
},
prettyFile: {
level: 'debug',
name: 'file.pretty.info',
filename: `./logs/${moment().format('YYYY-MM-DD')}-info.log`,
handleExceptions: true,
maxsize: 5242880, // 5MB
maxFiles: 100,
format: format.combine(
all(),
format.timestamp({
format: 'YYYY-MM-DD HH:mm:ss.SSS'
}),
format.align(),
format.printf(info => {
return `${info.timestamp} ${info.level}: ${formatObject(info.message)}`;
})
)
},
errorFile: {
level: 'error',
name: 'file.json.error',
filename: `./logs/${moment().format('YYYY-MM-DD')}-error.log`,
handleExceptions: true,
maxsize: 5242880, // 5MB
maxFiles: 100,
format: format.combine(
all(),
format.timestamp({
format: 'YYYY-MM-DD HH:mm:ss.SSS'
}),
format.align(),
format.printf(info => {
return `${info.timestamp} ${info.level}: ${formatObject(info.message)}`;
})
)
},
console: {
level: 'debug',
handleExceptions: true,
format: format.combine(
all(),
format.timestamp({
format: 'YYYY-MM-DD HH:mm:ss.SSSZZ'
}),
format.colorize(),
format.align(),
format.printf(info => {
return `${info.timestamp} ${info.level}: ${formatObject(info.message)}`;
})
)
}
};
// instantiate a new Winston Logger with the settings defined above
let logger = new createLogger({
transports: [
// new transports.File(options.jsonFile),
new transports.File(options.prettyFile),
new transports.File(options.errorFile),
new transports.Console(options.console)
],
exitOnError: false
});
// create a stream object with a 'write' function that will be used by `morgan`
logger.stream = {
write: function(message, encoding) {
// morgn is set to only log errors in production
process.env.NODE_ENV !== 'production'
? logger.info(message.replace(/^\s+|\s+$/g, '')) // prevent 2 new lines being inserted (removes \r\n)
: logger.error(message);
}
};
// Log routes with morgan - this goes in app.js
// process.env.NODE_ENV !== 'production'
// ? app.use(morgan('dev', { stream: logger.stream }))
// : app.use(
// morgan('combined', {
// stream: logger.stream,
// // Only log error messages
// skip: function(req, res) {
// return res.statusCode < 400;
// }
// })
// );
module.exports = logger;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment