banner image 1 banner image 2

Implementing a Custom Logger in Strapi v4 with log-rotate

June 29, 2022
3 mins
command
blog-img 1
Shuruthi V
Author

Use log-rotate to implement a custom logger in Strapi version 4

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.

  • Strapi logger exports createLogger, winston and formats in node_modules/@strapi/logger/lib/index.js.
  • Install @strapi/logger
  • Adding logger in config/middlewares.js at proper sequence
  • We are exporting winston from strapi logger. We are using winston-daily-rotate-file for rotating log files.

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
})
]
}
}
  • Initialise and export the important variable needed to create logger format.
  • Logger path (/docker-logs/strapiv4) directory is created to set all log files into it.
  • Here we have used “Winston” directly imported from @strapi/logger package.
  • Winston supports transport to write logs both on console and file too.
  • Logger file name is customised with containerId.
  • In addition to all we too take care of log rotation by using winston-daily-rotate-file.
  • And export the required.
  • Call the logger inside middleware.js inside strapi repo.
  • Make sure level should be out of transport while exporting.

Middleware.js (proper sequence):

The proper sequence for middleware.js
The proper sequence for middleware.js

How to use Custom Logs in Strapi v4:

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.

Example 1:

Const Strapi = new strapi.Strapi();
Strapi.log.info(“HelloWorld”);

Example 2:

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.


Reference:

[embed]https://docs.strapi.io/developer-docs/latest/setup-deployment-guides/configurations/required/middlewares.html#internal-middlewares-configuration-reference[/embed]

Meet the team!

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!
blog-img 2

Discussions

blog-img 3
5 mins
May 17, 2023
Sharing Data Between Controllers: Best Practices S...

This article will help you to understand the diffe

By Naveen C

blog-img 3
5 mins
March 21, 2023
Understanding Auto Layout and Constraints in Swift...

This article gives you an easy way of understandin

By Ramasamy P