If you want the object to be logged to the console and to the file, here is what you can do:
1.Initialize 2 formats. One for file and the other for the console. Notice the JSON.stringify
method used in the consoleFormat
const winston = require("winston");
const { format, transports, createLogger } = winston;
const path = require("path");
const consoleloggerLevel = process.env.WINSTON_LOGGER_LEVEL || "info";
const consoleFormat = format.combine(
format.colorize(),
format.timestamp(),
format.align(),
format.printf((info) => {
return `${info.timestamp} - ${info.level}: [${info.label}]: ${
info.message
} ${JSON.stringify(info.metadata)}`;
})
);
const fileFormat = format.combine(
format.timestamp(),
format.label({ label: path.basename(process.mainModule.filename) }),
format.metadata({ fillExcept: ["message", "level", "timestamp", "label"] }),
format.json()
);
2.Now, create the logger.
const logger = createLogger({
level: "info",
defaultMeta: { service: "some-random-service" },
format: fileFormat,
transports: [
new transports.File({
filename: path.join(__dirname, "../logs/error.log"),
level: "error",
}),
new transports.File({
filename: path.join(__dirname, "../logs/activity.log"),
maxsize: 5242880, //5MB
maxFiles: 5 // just in case
}),
],
});
3.Enable console logging only in non-prod environments:
if (process.env.NODE_ENV !== "production") {
logger.add(
new transports.Console({
level: consoleloggerLevel,
format: consoleFormat,
})
);
}
4.Export it as the default logger
module.exports = logger;
On logger.info("Server started listening", { port: 9000 } );
This will print,
On the console:
2021-06-22T07:47:25.988Z - info: [index.js]: Server started listening {"service":"some-random-service", "port": 9000}
In the file:
{"message":"Server started listening","level":"info","timestamp":"2021-06-22T07:47:25.988Z","label":"index.js","metadata":{"service":"some-random-service", "port": 9000}}