How to make logrotate use SSMTP
A few days ago I was looking at my server logs, my website logs are more than a year old and growing, so I was reading some of them and wanted to download the old logs, truncate the logs, so that next time I read the logs I won’t have to look at very old data. So basically I wanted to rotate the logs and archive them, luckily logrotate is there to let me manage and administer log files in my system. It has a long list of features with a very easy configuration, so it was the tool I’m looking for.
logrotate uses the system’s mail
/bin/mail to send the email when a log file is to be archived and removed from the system. But my system doesn’t use /bin/mail, it uses SSMTP with some custom configurations. I wanted to use SSMTP with logrotate but apparently it’s not a very simple task, since the man page for logrotate says:
Option -m, –mail
Tells logrotate which command to use when mailing logs. This command should accept two arguments: 1) the subject of the message, and 2) the recipient. The command must then read a message on standard input and mail it to the recipient. The default mail command is /bin/mail -s.
Which is not actually how SSMT works, SSMTP as it’s described in the man page accepts the recipients emails as command line arguments, and reads the message (along with it’s subject header) from the standard input.
The shell script
The solution to this problem would be by creating a shell script that behaves like a middleware between logrotate and SSMTP.
The shell script would simply read the arguments passed from logrotate and then build the right command to call SSMTP with by prepending the appropriate SMTP headers (To, Subject, From) to the message.
You can download the shell script from this link logrotate_ssmtp.sh.
As you can easily see that the shell script only accepts two arguments, so it sends the email to only one person, if you want to have more than one recipient and you’ve configured logrotate to send them the email, you’ll have to modify the script to accept more arguments and pass them to SSMTP.
Also you’ll have to replace
email@example.com with the email address you’re sending from.
Now all we have to do is to configure logrotate to use the shell script as a mail command instead of /bin/mail. To do so you’ll have to edit all the calls that you make to logrotate to be like:
/usr/sbin/logrotate -m '~/logrotate_ssmtp.sh' /etc/logrotate.conf
The main call that you should change is located in
cron.daily directory, I’m using Ubuntu so I have to edit this file
/etc/cron.daily/logrotate and change the command at the end of the file to the command above.
Hope this helps you with your logs 🙂