Upgrade from Winston 2 to 3 using colors

23 Oct 2022 in TIL

I updated a project from Winston 2 to Winston 3 this morning and needed to make a few changes to how it was configured.

I previously created a logger instance, then switched to using syslog levels with a custom colour scheme. Here's how I did it in Winston 2:

javascript
var winston = require("winston");
var logger = new winston.Logger({
transports: [
new winston.transports.Console({
level: "warning",
colorize: true,
}),
],
});
syslogColors = {
debug: "rainbow",
info: "cyan",
notice: "white",
warning: "yellow",
error: "bold red",
crit: "inverse yellow",
alert: "bold inverse red",
emerg: "bold inverse magenta",
};
winston.addColors(syslogColors);
logger.setLevels(winston.config.syslog.levels);

In Winston 3, the new winston.Logger call has been replaced with winston.createLogger, levels must be provided in the constructor, and formatting is handled by individual formatters using the logform library.

Here's how to achieve the same thing as above in Winston 3:

javascript
const winston = require("winston");
const syslogColors = {
debug: "rainbow",
info: "cyan",
notice: "white",
warning: "yellow",
error: "bold red",
crit: "inverse yellow",
alert: "bold inverse red",
emerg: "bold inverse magenta",
};
let format = winston.format.combine(
winston.format.colorize({
all: true,
colors: syslogColors,
}),
winston.format.simple()
);
var logger = winston.createLogger({
transports: [
new winston.transports.Console({
level: "warning",
format,
}),
],
levels: winston.config.syslog.levels,
});