Email yourself filtered logs and command output directly from your web server

When troubleshooting or checking your server, you often gather data that is interesting for further inspection or archiving. For instance a list of all brute force attacks from the past few days, or the number of 500 status codes generated by day. 

You can easily email these data to yourself, directly from the screen, using the mail command.

First check if the email command actually exists on your server

which mail

Sending yourself an email is as easy as:

echo "This is my email body" | mail -s "This is my subject" -t contact@joostvanveen.com

In other words: you can pipe the output on your screen the the mail command and mail that output to yourself. Say you want to mail yourself a list of the top 40 visitors by IP address from all rotated gzipped log files:

zcat /var/log/nginx/access.log* | awk '{print $2}' | sort | uniq -c | sort -nr | head -40 | mail -s "Top 40 visitors" -t contact@joostvanveen.com

You can also use the mail command to send attachments.

echo "Today's error log" | mail -s "Today's error log" -t contact@joostvanveen.com -A /var/log/nginx/error.log