In a logrotate conf there are the options of prerotate and postrotate where you can place scripts to be run.  The only issue is in most logrotate confs it applies to multiple files and therefore the prerotate and postroate scripts are run multiple times (for each occurrence of each file to be rotated).

I had the situation where I wanted the prerotate to scp apache/httpd access logs to a central AWStats server prior to rotating, and I only wanted the scp to occur once.  The only method I identified to work was to create a kind of pid file, or temp file, and check for its existence.  Below is the code incase anybody else requires a similar solution:

vim /etc/logrotate.d/apache

#-------------------------------------------------
# Log rotation for /usr/local/apache
#-------------------------------------------------
/usr/local/apache/logs/*log {
      daily
      rotate 10
      missingok
      compress
      notifempty
      prerotate
            #Unfortunately prerotate script is run on each occurrence which meets the above *log
            #search therefore in order to not have the files scp'd multiple times I have to 
            #create a temp file for today and check for its existence
            today=$(date +"%y-%m-%d")
            filename="/usr/local/apache/logs/logrotate$today"
            if [ ! -f "$filename" ]; then
                  #This should only be run once as the file is created later
                  scp /usr/local/apache/logs/*access_log awstats1:/usr/local/awstats/importLogs/$HOSTNAME/.
                  #Remove yesterdays temp file
                  rm -f /usr/local/apache/logs/logrotate*
                  #Create todays temp file to fail this if clause on subsequent iterations
                  touch $filename
            fi
      endscript
      postrotate
            /usr/local/apache/bin/apachectl graceful
      endscript
}
Tagged with →  
Share →

2 Responses to logrotate prerotate postrotate to run only once not multiple times

  1. Kit Gerrits says:

    Have you looked into the sharedscripts option?

Leave a Reply

Your email address will not be published. Required fields are marked *