環境はUbuntuを使用。アクセスログ解析ツールとしてGoAccessというツールもあるが、単純にシンプルなツールを使いたかったので、ngxtopを採用した。
使用方法
access_logのパスが/etc/nginx/nginx.confに記載されていれば
単純に以下のコマンドで監視が始まる。
$ ngxtop
自分の場合、一台のサーバで複数のサイトを運営しているため
access_logのパスはサーバ毎の設定ファイルに記述してある。
そのため上記のコマンドを打つと以下のエラーがでる。
$ ngxtop
Error: Access log file is not provided and ngxtop cannot detect it from your config file (/etc/nginx/nginx.conf).
こういった場合は、ログファイルの場所を指定することで使用できるようになる。
$ ngxtop -l /var/log/nginx/access.log
ちなみに余談だが、自分の場合は上記のコマンドでもngxtopが動作しなかった。
調べたところ、ログのフォーマットを独自フォーマットにしていたことが原因だった。
@shaun-ba This was happening to me too and my nginx config is using a custom log format, which turned out to be the issue. Check your nginx.conf file to see if you're doing the same (grep for log_format in the config directory) and if so, just pass ngxtop the config format and it works:
no data · Issue #83 · lebinh/ngxtop · GitHub
なので以下のようにログフォーマットを指定して実行することで、動作した。
$ ngxtop -f '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$http_x_forwarded_for" "gzip=$gzip_ratio"' -l /var/log/nginx/access.log
デフォルトだと現在既に出力されているaccess.logのデータは無視されるので
既存のaccess.logを元にしたデータが見たいときは"--no-follow"を指定する。
$ ngxtop -f '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$http_x_forwarded_for" "gzip=$gzip_ratio"' -l /var/log/nginx/access.log --no-follow
デフォルトだと10件までしか表示されないので、"-n"オプションを使って、100件表示させる
$ ngxtop -f '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$http_x_forwarded_for" "gzip=$gzip_ratio"' -l /var/log/nginx/access.log -n 100
また自分の場合、攻撃目的でアクセスしてくるログを見たいという用途があったため最終的に以下のコマンドになった。
$ ngxtop -f '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$http_x_forwarded_for" "gzip=$gzip_ratio"' -l /var/log/nginx/access.log -n 100 -i 'status >= 400' print request status http_referer http_x_forwarded_for
printで表示させるでデータは、nginxと同じものが指定できる。
備考
特定のIPを無視したいときは"-i"オプションを使用する
$ ngxtop -f '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$http_x_forwarded_for" "gzip=$gzip_ratio"' -l /var/log/nginx/access.log -n 100 -i 'status >= 400' print request status http_referer http_x_forwarded_for -i 'remote_addr != "xxx.xxx.xxx.xxx"'
[参考]
ngxtop - LinuxでリアルタイムでNginxログファイルを監視する
Monitor Nginx Log Files Using ngxtop on Ubuntu 20.04