Implementing a Custom Logger in Strapi v4 with log-rotate
By Shuruthi V, Rajesh krishnakumar and Krishna B.
In STRAPI, logger middleware is used to log requests.
To define a custom configuration for the logger middleware, create a dedicated configuration file (./config/logger.js). It should export an object that must be a complete or partial winston js (opens new window)logger configuration. The object will be merged with Strapi’s default logger configuration on server start.
Code:
APP_NAME = “strapi-v4”
NODE_ENV = “development”
LOGPATH = “/logger/strapi-v4”
LOG_FILE_NAME = `${LOGPATH}/${APP_NAME}-%DATE%-{{suffix}}.log`
onst { mkdirSync, existsSync } = require(“fs”);
const safeStringify = require(“fast-safe-stringify”);
const { winston } = require(‘@strapi/logger’);
const moment = require(“moment”);
require(“winston-daily-rotate-file”);
const { printf, combine, timestamp, label } = winston.format;
// Our Custom Format of Logging
const logCustomFormat = printf(
({ level, message, label, timestamp, stack, …info }) => {
return safeStringify({
timestamp,
label,
message,
info: info,
stack,
});
}
);
if (NODE_ENV === “development”) {
module.exports = {
transports: [
new winston.transports.Console({
format: combine(label({ label: APP_NAME }), timestamp(), logCustomFormat),
}),
],
}
}else{
module.exports = {
format: winston.format.combine(label({ label: APP_NAME }), timestamp(), logCustomFormat),
transports: [
new winston.transports.DailyRotateFile({
filename: LOG_FILE_NAME.replace(“{{suffix}}”, process.env.CONTAINER_ID),
datePattern: “YYYY-MM-DD”,
timestamp:moment().format(“DD/MM/YYYY”),
prepend: true,
handleExceptions: true
})
]
}
}
In strapiV4 we don’t have direct contact package access for error, debug, info, silly etc inside level. These are compacted inside a function constructor in strapi class .
So in order to access a property of level we ought to create an object for methods inside strapi class.
And load the object with Strapi() server.
Const Strapi = new strapi.Strapi();
Strapi.log.info(“HelloWorld”);
Const Strapi = new strapi.Strapi();
try
{
if(error)
{
Strapi.log.error(“error from method”,error)
}catch(err){
Strapi.log.error(“Uncaiught Exception”,err);
}
Plays a important role in custom logging of loggers through error.
Authors
Shuruthi V
Rajesh krishnakumar
Krishna B
Editor
Mridula Saravanan
We at CaratLane are solving some of the most intriguing challenges to make our mark in the relatively uncharted omnichannel jewellery industry. If you are interested in tackling such obstacles, feel free to drop your updated resume/CV to careers@caratlane.com!
Leave a Reply