If you’re running Node.js applications in production, PM2 is a lifesaver for process management. However, log handling is often overlooked—Managing Large PM2 Log Files is critical, as unmanaged logs can grow rapidly and consume valuable server disk space.
The Problem
By default, PM2 generates logs for your Node.js applications. In development, this isn’t a big deal—but in production, it can become a huge problem.
We noticed that PM2 log file had grown to large log file size due to repeated application logs. This will make the entire server space to occupy.
A quick check with:
du -h ~/.pm2/pm2.log
confirmed the massive size of the log.
The Wrong Way to Delete Logs
Initially, We will try “delete the log file” approach:
// DANGER: DO NOT DO THIS!
rm ~/.pm2/pm2.log
This doesn’t work because the PM2 process still holds the file open. The disk space won’t be freed until PM2 is restarted or the server is rebooted.
The Right Way: PM2 Flush
PM2 provides a proper way to clear logs:
pm2 flush
This command clears the logs in the main ~/.pm2/pm2.log file. You can reboot afterward to ensure everything resets, but flushing alone usually solves the space issue.
Preventing Future Problems: Log Rotation
The key lesson: implement log rotation. PM2 has a built-in module called pm2-logrotate that handles this elegantly.
Step 1: Install pm2-logrotate
pm2 install pm2-logrotate
Step 2: Configure Your Rotation Settings
Here’s an example that works well for production:
pm2 set pm2-logrotate:max_size 100M # Rotate logs once they reach 100MB
pm2 set pm2-logrotate:retain 10 # Keep the last 10 rotated logs
pm2 set pm2-logrotate:compress true # Compress old logs
Default Settings
If you need to reset, these are PM2’s default values:
pm2 set pm2-logrotate:retain 30
pm2 set pm2-logrotate:compress false
pm2 set pm2-logrotate:dateFormat YYYY-MM-DD_HH-mm-ss
pm2 set pm2-logrotate:max_size 10M
pm2 set pm2-logrotate:rotateInterval 0 0 * * *
pm2 set pm2-logrotate:rotateModule true
pm2 set pm2-logrotate:workerInterval 30
With log rotation enabled, your log files will:
- Stay within manageable size limits
- Be automatically compressed
- Delete old logs after a set number of rotations
This ensures your server never runs out of disk space due to runaway logs.
Key Takeaways
- Don’t manually delete PM2 logs while processes are running—they will still occupy disk space.
- Use pm2 flush to safely clear logs.
- Always implement log rotation in production to prevent disk space issues.
PM2 is fantastic for process management, but without log rotation, even the best tools can lead to headaches. A few commands can save you from a huge log disaster.
If Managing Large PM2 Log Files is becoming a challenge and putting your server at risk of disk space issues, our expert help can make all the difference. With reliable Server Management Services, professionals can monitor log growth, implement proper log rotation, and proactively prevent storage disasters.