Managing Disk Space with PM2 Log Rotation and Retention Policies
Unmanaged application logs can exhaust disk space. PM2 automates cleanup using flags like --log-expire-time and --log-size, allowing for controlled, environment-specific log retention policies.
16 May 2026, 03:44 UTC

Prevent Uncontrolled Disk Growth from Node.js Logs
The problem is that unmanaged application logs, especially from high-traffic Node.js services managed by PM2, can consume excessive disk space, leading to application instability or storage exhaustion. The useful takeaway is that PM2 provides granular flags—specifically --log-expire-time and --log-size—to automate log cleanup without manual intervention.
Configuring Log Limits in PM2
Log rotation is managed either via command-line arguments during startup or within the ecosystem.config.js file, allowing environment-specific policies.
--log-size: Sets the maximum size (e.g., 100M) a log file can reach before PM2 rotates it to a new file.--log-expire-time: Defines how long (e.g., 7d for 7 days) PM2 should keep rotated log files before automatically truncating (deleting) them.--log-date-format: Customizes the timestamp format within the logs, aiding external log aggregators (like ELK stack) in parsing.
Practical Configuration Example
To deploy a service that rotates logs at 100MB and retains them for 14 days, use the following configuration within ecosystem.config.js:
module.exports = {
apps: [
{
name: "my-node-app",
script: "./app.js",
instances: 1,
log_file: "./logs/app.log",
log_size: "100M",
log_expire_time: "14d",
log_date_format: "YYYY-MM-DD HH:mm:ss"
}
]
};Note: PM2 versions supporting these flags are assumed (e.g., v4+). Ensure the process is started using pm2 start ecosystem.config.js.
Verification and Health Checks
After allowing time for rotation to occur (based on size or time), verify the system state:
- Run
pm2 logs my-node-app --lines 10to confirm recent entries are present. - Check the log directory manually to confirm the oldest file timestamp aligns with the 14-day retention policy.
- Execute
pm2 listto ensure the process remains healthy (status: 'online') after the cleanup operation.
Recovery Considerations
The primary risk is setting --log-expire-time too aggressively, losing critical debugging data. If logs are unexpectedly missing, first verify the process status using pm2 list. If the process is healthy, check the log directory timestamps against the configured expiration to confirm the policy executed as intended. There is no state change rollback for log deletion; review the retention period before deployment.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.