Bash

Rotate Logs Manually

admin by @admin ADMIN
1h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
If a service doesn't hook into logrotate, you can still rotate a log file yourself in one safe pattern: rename current → .1, truncate the original, signal the process to re-open if needed.
Bash
Raw
LOG="/var/log/myapp/app.log"
MAX_AGE_DAYS=14

# Rotate if larger than 50 MB
if [[ -f "$LOG" && $(stat -c%s "$LOG") -gt 52428800 ]]; then
    STAMP="$(date -u +%Y%m%d-%H%M%S)"
    mv "$LOG" "$LOG.$STAMP"
    gzip "$LOG.$STAMP"                  # background it if log is huge
    # Tell the app to reopen if needed
    pkill -USR1 -f myapp || true        # SIGUSR1 = "reopen logs" by convention
fi

# Clean up archives older than 14 days
find "$(dirname "$LOG")" -name "*.gz" -type f -mtime +$MAX_AGE_DAYS -delete

# Or just use logrotate (the right answer for anything long-term):
# /etc/logrotate.d/myapp:
#   /var/log/myapp/*.log {
#       daily; rotate 14; compress; delaycompress; missingok; notifempty;
#       postrotate; systemctl reload myapp; endscript
#   }
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.