6

I have some server applications running on apache2; Ruby on Rails, PHP and others.

In all cases I would like apache to send me an email whenever apache responds a HTTP error 500 Internal server error.

How can I do that?

Jarl
  • 2,831
  • 4
  • 24
  • 31

3 Answers3

11

One way you can do this is use a php script that sends email, as well as output some sort of 500 message. Then use the ErrorDocument directive:

ErrorDocument 500 /path/to/script/that/sends/email.php
Jon Lin
  • 142,182
  • 29
  • 220
  • 220
  • Thanks for an excellent workaround. However the applications all have some custom pages for error 500. A typical rails application have a file public/500.html that is shown upon an internal server error. Your proposal would interfere with these application specific error documents. – Jarl Aug 31 '12 at 06:51
  • @Jarl Well, something else you can try is parsing the apache log files, or write something that reads output from `tail -f` – Jon Lin Aug 31 '12 at 06:59
10

It is not possible to configure apache to send emails.

There are some things you can do to achieve the same result:

  1. You can use the ErrorDocument directive to let it point to some CGI script, that be a perl, PHP, or any other server-side executed script. The script can then send an email and respond a Error 500 document.

  2. You can use some external tool to watch your apache log files and configure theese tools to send you emails. There are several tools and ways to do this. For Linux many tools and methods are suggested on https://serverfault.com/questions/45246/linux-monitor-logs-and-email-alerts

  3. Write an apache module. I think that mod_tee is a good starting point.

Community
  • 1
  • 1
Jarl
  • 2,831
  • 4
  • 24
  • 31
  • ErrorDocument catches only Apache errors, and not PHP fatal errors. [Source](https://stackoverflow.com/questions/5765319/apaches-errordocument-directive-does-not-redirect/5839076#5839076) – wast Aug 07 '18 at 08:27
4

Create a script called log_monitor.sh:

#!/usr/bin/perl -w

use strict;

my $cachefile="/var/cache/lastpos-apache2-scan4maxclntOrSigKill";
my $logfile="/var/log/httpd/error_log";
my $searchstr=" 500 ";

my $lastpos=0;
if (-f $cachefile) {
    open FH,"<".$cachefile;
    $lastpos=<FH>;
    close FH;
};

my $newpos=(stat $logfile)[7];

open FH,"<".$logfile;
seek FH,$lastpos,0;
while (<FH>) {
    print if m/$searchstr/i;
};
close FH;

open FH,">".$cachefile;
print FH $newpos;
close FH;

modify $searchstr as needed. note the spaces around "500", since you don't want to match errors which contain a 404 on a file that has "500" in its path or filename (among other places).

configure the script to run every X minutes via cron. the greater the value of X, the less emails you will get (only 1 email every X minutes for all the errors that match the strings you supply). the results of the cron job will get emailed to you automatically (if cron is setup properly)

Gaia
  • 2,872
  • 1
  • 41
  • 59