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

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

Logwatchには、Nginxのログを解析・レポートするための設定がデフォルトではありません。そこで、Apacheの設定ファイルを基に、Nginx用の設定ファイルを作成する方法を紹介します。

設定は、以下のサイトを参考にさせていただきました。ありがとうございます。

https://server-setting.info/centos/logwatch-nginx-setting.html#nginx_logwatch_5

動作環境

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

# cat /etc/redhat-release
CentOS Linux release 7.4.1708 (Core)

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

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

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・回数」などが解析レポートに記載されており、問題なく解析できていると思われます。