linuxbashcronlogrotate

logrotate not running prerotate script


I have a script I wrote to parse my nginx logs and email the result to me, which I added to my nginx logrotate script, but it is not working...

/var/log/nginx/*.log {
        daily
        missingok
        rotate 14
        compress
        delaycompress
        notifempty
        create 0640 www-data adm
        sharedscripts
        prerotate
                /root/bin/nginx-parse.sh
                if [ -d /etc/logrotate.d/httpd-prerotate ]; then \
                        run-parts /etc/logrotate.d/httpd-prerotate; \
                fi \
        endscript
        postrotate
                invoke-rc.d nginx rotate >/dev/null 2>&1
        endscript
}

The script is in the prerotate section and it works when I call it as the root user, which is what I believe logrotate runs as.

I can see when I run logrotate -d -f /etc/logrotate.d/nginx that it does not email anything to me.

Where should I go from here?

alert-mail.sh.sh:

#!/usr/bin/python
import smtplib
import sys
from email.mime.text import MIMEText

server = smtplib.SMTP('smtp.example.com', 587)
server.starttls()
server.login("me@example.com", "secret")

# Create message
msg = MIMEText(sys.argv[2])
msg['Subject'] = sys.argv[1] 
msg['From'] = "me@example.com" 
msg['To'] = "me@example.com"

server.sendmail(msg["From"], [msg["To"]], msg.as_string())
server.quit()

nginx-parse.sh

#!/bin/bash
# For parsing of the nginx logfile and emailing to myself

rm /root/bin/nginx_email.txt
printf "NGINX STATUS CODES\n\n" >> /root/bin/nginx_email.txt
cat /var/log/nginx/access.log | cut -d '"' -f3 | cut -d ' ' -f2 | sort | uniq -c | sort -rn >> /root/bin/nginx_email.txt
printf "\n\n404 URLS\n\n" >> /root/bin/nginx_email.txt
awk '($9 ~ /404/)' /var/log/nginx/access.log | awk '{print $7}' | sort | uniq -c | sort -rn  >> /root/bin/nginx_email.txt
printf "\n\n502 URLS\n\n" >> /root/bin/nginx_email.txt
awk '($9 ~ /502/)' /var/log/nginx/access.log | awk '{print $7}' | sort | uniq -c | sort -r >> /root/bin/nginx_email.txt
printf "\n\nMOST ACCESSES URLS\n\n" >> /root/bin/nginx_email.txt
awk -F\" '{print $2}' /var/log/nginx/access.log | awk '{print $2}' | sort | uniq -c | sort -rg | head -n 50 >> /root/bin/nginx_email.txt

#Sending the email using the python script I wrote
alert-mail "NGINX PARSING" "$(cat /root/bin/nginx_email.txt)"

Solution

  • I understand that the /root/bin/nginx-parse.sh script sends you the email. When it is ran from logrotate, make sure that the binaries for commands like mail have full path (e.g. /usr/bin/mail instead of just mail). What are the contents of your script? Also, run the logrotate with -v flag: logrotate -d -v -f /etc/logrotate.d/nginx