Recently I encountered a scenario where an application generates timestamped log files in the format app.log.DD_MM_YYYY
, and I needed to clean up these old logs without actually rotating them. While logrotate is typically used for rotation, it can also handle pure deletion of log files when configured properly.
My first configuration attempt looked like this:
/opt/log/app/app.log.* {
rotate 0
missingok
nomail
}
This didn't work because logrotate expects to perform some form of rotation by default.
After some research and testing, I found the correct configuration needs these additional parameters:
/opt/log/app/app.log.* {
daily
rotate 0
missingok
nocreate
nocompress
notifempty
nomail
}
- rotate 0: Immediately removes old logs rather than keeping any rotations
- nocreate: Prevents logrotate from creating a new empty log file
- nocompress: Skip compression since we're just deleting
- notifempty: Don't rotate if empty (though we're deleting anyway)
If you prefer more control, a simple bash script in cron might be better:
#!/bin/bash
# Delete logs older than 30 days
find /opt/log/app/app.log.* -mtime +30 -exec rm {} \;
Logrotate is better when:
- You want to leverage existing logrotate infrastructure
- Need integration with other log rotation policies
A custom script is better when:
- You need complex deletion criteria
- Want to avoid logrotate's learning curve for simple tasks
Always test with:
logrotate -d /etc/logrotate.conf
The -d
flag performs a dry run showing what would happen.
When dealing with timestamped log files like app.log.DD_MM_YYYY
, traditional log rotation becomes tricky because:
- The files already contain rotation semantics in their names
- Standard rotation would create redundant copies (app.log.DD_MM_YYYY.1)
- We only need cleanup - not actual rotation
Your attempted configuration was close. Here's the proper setup:
/opt/log/app/app.log.* {
daily
rotate 0
missingok
nomail
nocreate
nocompress
notifempty
sharedscripts
postrotate
# Optional: Any post-deletion commands
/bin/true
endscript
}
Key directives explained:
rotate 0
: Immediately deletes matched filesnocreate
: Prevents new empty log creationsharedscripts
: Runs postrotate once for all files
For those preferring a more direct approach:
# In crontab -e
0 3 * * * find /opt/log/app/ -name "app.log.*" -mtime +30 -exec rm {} \;
This deletes files older than 30 days at 3AM daily.
Test your configuration with:
sudo logrotate -dv /etc/logrotate.conf
Common pitfalls:
- Wrong file permissions (needs read access to log dir)
- Missing
nocreate
causing empty log files - Incorrect glob pattern matching
Here's a complete solution we use for Apache timestamped logs:
/var/log/apache2/*.log.20* {
weekly
rotate 0
missingok
compress
delaycompress
notifempty
nocreate
sharedscripts
postrotate
/etc/init.d/apache2 reload > /dev/null
endscript
}