how can i rotate log files in pino.js logger

Viewed 3377

I am trying to use pino for logging in to my node app Server and I do have some large logs coming, so rotating the files every day would be more useful for reading the logs afterwards.

I can do this using morgan but with pino I can't find a way to do it. I tried to dynamically assign the folder based on the current date but doing so in the main app.js file means it will only run once and cycling date would mean stopping and rerunning the server.

Here is my code:

var date = d.getFullYear()+'-'+(d.getMonth()+1)+'-'+d.getDate();
const fileLogger = pino(
     pino.destination({
          dest: './log/userLog '+date, sync: false
     })
);
2 Answers

As stated in pino documentation you need to use a separate tool for log rotation.

Using logrotate you can do it easily.

node myapp.js > /var/log/myapp.log

Install logrotate on you server and create a /etc/logrotate.d/myapp file with the logrotation config, e.g.:

/var/log/myapp.log {
   su root
   daily
   rotate 7
   delaycompress
   compress
   notifempty
   missingok
   copytruncate
}

Be sure to read its configuration documentation to achieve your rigth rotation. Obviously, explore the many other questions about logrotate if you have problems with it.

Using logrotate is a viable approach. But the pino-rotating-file transport for pino seems a better idea.

Related