DEV Community

loading...
Cover image for Day 40 of #100DaysOfCode: Node.js Express Logging (Export and Rotate Files)

Day 40 of #100DaysOfCode: Node.js Express Logging (Export and Rotate Files)

jenhsuan profile image Jen-Hsuan Hsieh ・1 min read

Introduction

This post is the note for Node.js Express logging.

Step 1. Install packages

npm install -s pino express-pino-logger logrotator
Enter fullscreen mode Exit fullscreen mode

Step 2. Add middlewares to the server

//Export the log files under logs folder
const logger = require("pino")('./logs/info.log');
const expressPino = require("express-pino-logger")({
  logger: logger
});
app.use(expressPino);

var logrotate = require('logrotator');

// use the global rotator
var rotator = logrotate.rotator;
// check file rotation every 5 minutes, and rotate the file if its size exceeds 1 mb.
// keep only 10 rotated files and compress (gzip) them.
rotator.register('./logs/info.log', {schedule: '5m', size: '1m', compress: true, count: 10});

rotator.on('error', function(err) {
  logger.error('oops, an error occured!');
  //console.log('oops, an error occured!');
});

// 'rotate' event is invoked whenever a registered file gets rotated
rotator.on('rotate', function(file) {
  logger.info('file ' + file + ' was rotated!');
  //console.log('file ' + file + ' was rotated!');
});
Enter fullscreen mode Exit fullscreen mode

That's it!

Articles

There are some of my articles. Feel free to check if you like!

Discussion (0)

pic
Editor guide