Skip to content

Instantly share code, notes, and snippets.

@x1unix
Last active December 2, 2021 19:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save x1unix/eece27a81541e61081536fab3e332ca3 to your computer and use it in GitHub Desktop.
Save x1unix/eece27a81541e61081536fab3e332ca3 to your computer and use it in GitHub Desktop.
Better console log formatter for Winston

About

This is a logrus-like improved CLI formatter for Winston.

Formatter supports labels and errors prerry print (from error field).

Output example

image

'use strict';
const winston = require('winston');
const colors = require('colors/safe');
const { format } = require('date-fns');
const formatLabel = ({label, ...entries}) => ({
...entries,
label: label ? colors.dim(`[${label}]`.toUpperCase()) : null
})
const formatLogLevel = level => {
let lvlString = level;
let colorFunc = colors.gray;
switch (level) {
case "info":
lvlString = "inf";
colorFunc = colors.green;
break;
case "warn":
lvlString = "wrn";
colorFunc = colors.yellow;
break;
case "error":
lvlString = "err";
colorFunc = colors.red;
break;
case "debug":
lvlString = "dbg";
break;
default:
break;
}
return colorFunc(lvlString.toUpperCase());
}
const formatLogEntries = entries => {
let keys = Object.keys(entries);
if (!keys.length) {
return null;
}
return Object.entries(entries)
.filter(([k]) => k !== 'label')
.map(([k, v]) => {
if (k === "error") {
return colors.red(`${k}=${JSON.stringify(v.toString())}`)
}
return `${colors.cyan(k + '=')}${JSON.stringify(v)}`
}).join(' ')
}
const logFormatters = [
winston.format.timestamp({
format: format(new Date(), 'HH:mm:ss')
}),
winston.format(formatLabel)(),
winston.format(({level, timestamp, message, ...msg}) => ({
...msg,
level: formatLogLevel(level),
timestamp: colors.gray(timestamp),
message: level === 'error' ? colors.red(message) : message
}))(),
winston.format.printf(
({label, timestamp, level, message, ...rest}) => (
[timestamp, label, level, message, formatLogEntries(rest)].filter(v => !!v).join(' ')
)
)
];
const defaultOpts = {
transports: new winston.transports.Console({
format: winston.format.combine(...logFormatters)
})
};
const newLogger = level => winston.createLogger({
...defaultOpts,
level
});
exports.newLogger = newLogger;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment