A good approach for saving Strapi logs into a log file?

Viewed 1019

I am looking for a simple approach in order to store the logs from my Strapi app into a file rather than just receiving them in the console. From documentations I couldn't find a good way to achieve that. Do you have any suggestion?

1 Answers

Well you can use any of the loggers of your choice like Winston, Simple Node Logger Etc. I've personally used Simple Node Logger.

So, firstly create a helpers folder in the root of your strapi project. Then create a logger.js file in it. Add the following code to the logger file.

// helpers/logger.js
const simpleLogger = require('simple-node-logger');

const logger = simpleLogger.createRollingFileLogger({
  logDirectory: 'logs/',
  fileNamePattern: 'strapi_log_<DATE>.log',
  dateFormat: 'YYYY.MM.DD',
});

module.exports = logger;

Next, create the /logs folder in the root of your project. Finally, require the logger in your controller or service file and log messages to the log files. Simple Node Logger will handle the process of rolling log files and log filenames on daily basis for you.

// api/restaurants/controller/index.js
const logger = require('../../../helpers/logger');

module.exports = {
  async someFindMethod(ctx){
    logger.info('Log information to log files');
    logger.error('Log error to log files');
    return 'Hello World!';
  }
}
Output
## logs/strapi_log_2021.10.14.log
11:14:36.048 INFO  Log information to log files 
11:14:36.048 INFO  Log error to log files
Sidenote:

To avoid server restarts on changes in log file, you need to ignore the folder by adding watchIgnoreFiles: ['**/logs/**'] to your config/server.js file in Strapi v3 (Check here) or to you config/admin.js file if your on Strapi v4 (Check here).

Related