【问题标题】:How can I configure apache to send an email on every HTTP error 500如何配置 apache 以在每个 HTTP 错误 500 上发送电子邮件
【发布时间】:2012-08-25 22:57:44
【问题描述】:

我有一些在 apache2 上运行的服务器应用程序; Ruby on Rails、PHP 等。

在所有情况下,只要 apache 响应 HTTP 错误 500 内部服务器错误,我都希望 apache 向我发送一封电子邮件。

我该怎么做?

【问题讨论】:

    标签: http apache httpd.conf


    【解决方案1】:

    您可以做到这一点的一种方法是使用发送电子邮件的 php 脚本,以及输出某种 500 消息。然后使用ErrorDocument 指令:

    ErrorDocument 500 /path/to/script/that/sends/email.php
    

    【讨论】:

    • 感谢您提供出色的解决方法。然而,这些应用程序都有一些错误 500 的自定义页面。典型的 Rails 应用程序有一个文件 public/500.html,它会在内部服务器错误时显示。您的提议会干扰这些特定于应用程序的错误文档。
    • @Jarl 好吧,你可以尝试解析 apache 日志文件,或者写一些从 tail -f 读取输出的东西
    【解决方案2】:

    无法配置 apache 发送电子邮件。

    你可以做一些事情来达到同样的效果:

    1. 您可以使用ErrorDocument directive 让它指向一些CGI 脚本,可以是 perl、PHP 或任何其他服务器端执行的脚本 脚本。然后脚本可以发送电子邮件并响应错误 500 文件。

    2. 您可以使用一些外部工具来查看您的 apache 日志 文件并配置这些工具以向您发送电子邮件。有几种工具和方法可以做到这一点。对于 Linux 许多 建议的工具和方法 https://serverfault.com/questions/45246/linux-monitor-logs-and-email-alerts

    3. 编写一个 apache 模块。我认为 mod_tee 是一个很好的起点。

    【讨论】:

    • ErrorDocument 仅捕获 Apache 错误,而不捕获 PHP 致命错误。 Source
    【解决方案3】:

    创建一个名为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;
    

    根据需要修改$searchstr。请注意“500”周围的空格,因为您不想匹配在路径或文件名(以及其他位置)中包含“500”的文件中包含 404 的错误。

    将脚本配置为通过 cron 每 X 分钟运行一次。 X 的值越大,您收到的电子邮件就越少(对于与您提供的字符串匹配的所有错误,每 X 分钟只有 1 封电子邮件)。 cron 作业的结果将自动通过电子邮件发送给您(如果 cron 设置正确)

    【讨论】:

    • 此脚本如何知道我的电子邮件 ID?
    • @ShahAbazKhan 脚本使用 cron 使用的电子邮件地址。它没有在脚本中设置。
    猜你喜欢
    • 1970-01-01
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    • 2016-11-02
    • 2016-06-08
    • 2013-01-24
    • 1970-01-01
    • 2013-07-06
    相关资源
    最近更新 更多