LogwatchでNginxのログを解析する方法

LogwatchでNginxのログを解析する方法

Linuxでのログ解析ツールとして一般的な「Logwatch」では、デフォルトでさまざまなソフトウェアのログを解析できますが、Webサーバーとして人気のNginxのログはデフォルトでは解析できず、ログを解析・レポートするためには設定ファイルを用意する必要があります。

そこでここでは、LogwatchでNginxのログを解析するための設定方法を紹介します。

この記事は、以下の環境で実行した結果を基にしています。他のエディションやバージョンでは、動作結果が異なる場合があることをご了承ください。

ソフトウェアバージョン
CentOS Linux7.4.1708

Nginxのログを解析するための設定

Apache用の設定ファイルをコピー

LogwatchでNginxのログを解析するには、まずApache用の設定ファイルをnginx用にコピーします。

アクセスログ用、エラーログ用それぞれで3ファイルずつ(プログラム、監視対象の設定ファイル、ログの設定ファイル)コピーします。

アクセスログ用:

# cp /usr/share/logwatch/scripts/services/http /etc/logwatch/scripts/services/nginx
# cp /usr/share/logwatch/default.conf/services/http.conf /etc/logwatch/conf/services/nginx.conf
# cp /usr/share/logwatch/default.conf/logfiles/http.conf /etc/logwatch/conf/logfiles/nginx.conf

エラーログ用:

# cp /usr/share/logwatch/scripts/services/http-error /etc/logwatch/scripts/services/nginx-error
# cp /usr/share/logwatch/default.conf/services/http-error.conf /etc/logwatch/conf/services/nginx-error.conf
# cp /usr/share/logwatch/default.conf/logfiles/http-error.conf /etc/logwatch/conf/logfiles/nginx-error.conf

設定ファイルの修正

コピーした設定ファイルをnginx用に修正します。

/etc/logwatch/conf/services/nginx.conf

「Title =」と「LogFile =」の行を以下のように修正します。

Title = "nginx"
LogFile = nginx

/etc/logwatch/conf/services/nginx-error.conf

「Title =」と「LogFile =」の行を以下のように修正します。

Title = "nginx errors"
LogFile = nginx-error

/etc/logwatch/conf/logfiles/nginx.conf

既存の「LogFile = 」の行をすべて削除して、以下を追記します。

LogFile = nginx/*access.log*

既存の「Archive = 」の行をすべて削除して、以下を追記します。

Archive = nginx/*access.log.*.gz

/etc/logwatch/conf/logfiles/nginx-error.conf

既存の「LogFile = 」の行をすべて削除して、以下を追記します。

LogFile = nginx/*error.log*

既存の「Archive = 」の行をすべて削除して、以下を追記します。

Archive = nginx/*error.log-*.gz

以上で、設定完了です。

動作確認

設定を完了したら以下のコマンドを実行して、nginxのレポートが標準出力に出力されるか確認します。

# logwatch --output stdout --service nginx
################# Logwatch 7.4.0 (04/19/18) #################
~省略~
----------------------- nginx Begin --------------------------
~省略~
------------------------ nginx End ---------------------------

あとがき

実行してみると「データ転送量」「応答コード別の応答数」「不正アクセスと推察されるアクセス元のIPアドレス・リクエストURI・回数」などが解析レポートに記載されており、問題なく解析できていると思われます。