Apache:ErrorLog 可以記錄主機名稱而不是 IP 位址嗎?

Apache:ErrorLog 可以記錄主機名稱而不是 IP 位址嗎?

在低負載 int 中擁有不同的 Apache 伺服器net 幾乎只有 DHCP 用戶端,我們需要記錄主機名稱而不是 IP 位址。由於 DHCP 環境非常動態,因此日後任何將 IP 重新對應到主機名稱的嘗試很可能會產生錯誤結果。

雖然我們有“ HostnameLookups On”,但只有訪問日誌會乖乖地記錄主機名,但錯誤日誌不會。

閱讀有關 的內容ErrorLogFormat,我注意到沒有%H, 只是%A(意思是「客戶端IP位址和連接埠」)。

那麼真的沒有辦法讓 apache 在錯誤日誌中記錄主機名稱嗎...?

答案1

不是本機的 ErrorLog 指令。

我要做的就是編寫腳本來為您解決問題並透過該腳本傳遞錯誤日誌。在你的 apache 設定中是這樣的:

Errorlog "|/usr/local/bin/errorlog_resolver.pl"

然後是範例 Perl 腳本:

#!/usr/bin/perl -w
# errorlog_resolver.pl

# Give apache ErrorLog on STDIN, outputs them with numeric IP addresses
# in the likely (host) field converted to hostnames (where possible).

# based on clf_lookup.plx from "Perl for Web Site Management"
# http://oreilly.com/catalog/perlwsmng/chapter/ch08.html
#

use strict;
use Socket;

open LOGFILE, ">>/tmp/my_error_log" or die "Couldn't open file: $!";
my %hostname;

while (<>) {
    my $line = $_;
    my($day, $month, $dayn, $hour, $year, $err, $client, $host, $rest) = split / /, $line, 9;
    if ( $client ~~ "[client" ) {
    # remove the ] trailing the likely ip-address.
      my $chr = chop($host);

      if ($host =~ /^\d+\.\d+\.\d+\.\d+$/) {
        # looks vaguely like an IP address
        unless (exists $hostname{$host}) {
            # no key, so haven't processed this IP before
            $hostname{$host} = gethostbyaddr(inet_aton($host), AF_INET);
        }
        if ($hostname{$host}) {
            # only processes IPs with successful lookups
            $line = "$day $month $dayn $hour $year $err $client $hostname{$host}\($host\)\] $rest)";
        }
      }
    }
    print LOGFILE $line;
}

相關內容