nginx コンテナのログを Logwatch で拾う


Logwatch は基本的にログファイルを監視するツールです。しかし、コンテナのログはファイルではなく podman logs や docker logs コマンドで参照する作りになっていることが多いです。今回 nginx コンテナを立ててログドライバーを変更し、コンテナのログをホストの journald に貯めるようにしたので journald から取得できないか試してみました。

Logwatch 自体はホスト側にインストールします。

ダミーファイル作成

何かしら内容のあるファイルを指定しないと動作しないので、ダミーファイルを作成します。

echo "dummy" > /etc/logwatch/dummy.txt

ログ定義を書き換え

Logwatch 標準の http.conf ログ定義をユーザー定義のファイル置き場にコピーします。http.conf 以外に http-error.conf というものもありますが、 nginx に対応していないようなので今回は不要です。

cp /usr/share/logwatch/default.conf/logfiles/http.conf /etc/logwatch/conf/logfiles/http.conf

/etc/logwatch/conf/logfiles/http.confを以下の内容で置き換えます。CONTAINER_NAME=nginx は podman run –name で指定したコンテナ名で置き換えてください。

########################################################
#   Define log file group for nginx
########################################################

# Clear out LogFile and give a dummy file
LogFile = 
LogFile = "/etc/logwatch/dummy.txt"

*JournalCtl = "-o cat CONTAINER_NAME=nginx"

*ExpandRepeats
*ApplyhttpDate

# vi: shiftwidth=3 tabstop=3 et

*JournalCtl の中身は、普通に journalctl コマンドを使用する際の引数と同じなので、さらに絞り込むことも可能です。

テスト

以下のコマンドを実行し、標準出力に結果が出れば成功です。

logwatch --output stdout --service http --range today
 
 ################### Logwatch 7.4.3 (04/27/16) #################### 
        Processing Initiated: Mon Aug 10 19:30:00 2020
        Date Range Processed: today
                              ( 2020-Aug-10 )
                              Period is day.
        Detail Level of Output: 0
        Type of Output/Format: stdout / text
        Logfiles for Host: example.com
 ################################################################## 
 
 --------------------- httpd Begin ------------------------ 

 Requests with error response codes
    404 Not Found
       /favicon.ico: 3 Time(s)
       /index.php: 3 Time(s)
       /: 2 Time(s)
 
 ---------------------- httpd End ------------------------- 

 
 ###################### Logwatch End ######################### 

設定ファイルのパス

logwatch 標準のファイル置き場
/usr/share/logwatch/scripts/services
/usr/share/logwatch/default.conf/services
/usr/share/logwatch/default.conf/logfiles

ユーザー定義のファイル置き場
/etc/logwatch/scripts/services
/etc/logwatch/conf/services
/etc/logwatch/conf/logfiles

conf/service がサービスの定義ファイル置き場、scripts/services がサービスのログを解析するスクリプト、conf/logfiles がログファイルの定義です。サービス定義とログファイル定義は N:1 になります。

例えば、 maillog のログファイル定義は1つですが、 qmail サービスや postfix サービスなどが maillog を参照しています。

コンテナを複数立ち上げた場合は、これらの設定をコピー&名前変更しては位置すればよさそうです。

script のデバッグ

以下のように debug オプションを追加すると、デバッグ用のメッセージが出ます。 8 が最大ですが、メッセージ多すぎるので調整が必要です。script を書き換える場合は参考になると思います。

logwatch --output stdout --service nginx --range today --debug 5

まとめ

最初は Prometheus と Grafana を入れたかったのですが、小規模なサーバーですしメモリが足りないので、軽量に動作する Logwatch を採用しました。結構昔からあるものですが、最近の環境にも対応していてありがたいです。今後もお世話になろうと思います。

参考


コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください