Introduction
This post is the note for Node.js Express logging.
- Use pino, express-pino-logger to generate the log file
- Use Logrotator to separate log files when the log file becomes too large
Step 1. Install packages
npm install -s pino express-pino-logger logrotator
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!');
});
That's it!
Articles
There are some of my articles. Feel free to check if you like!
- My blog-posts for software developing: https://medium.com/a-layman
- My web resume: https://jenhsuan.github.io/ALayman/cover.html
- Facebook page: https://www.facebook.com/imalayman
- Twitter bot: https://twitter.com/ALayman84368087
Top comments (0)