Chuyển đến nội dung chính

第3課:Nginxのロギングとモニタリング

アクセスログ、エラーログ、カスタムログフォーマット、ログローテーションなど、Nginxのロギングとモニタリングを学びます。 ログの分析、トラブルシューティング、logrotateの使用、サーバーパフォーマンスを追跡するための基本メトリクスについて解説します。 実用的な例とベストプラクティスを含みます。

🔒 DevSecOps — 第3課 第3課:Nginxのロギングとモニタリング

Nginxの基礎から応用まで

第1部:基礎

xdev.asia

1. アクセスログとエラーログ

Nginxにはサーバーの活動を監視するための2種類の主要なログがあります:アクセスログ(すべてのリクエストを記録)とエラーログ(エラーや警告を記録)。

1.1. アクセスログ

アクセスログはサーバーへのすべてのリクエストを記録し、クライアント情報、リクエスト、レスポンスステータス、処理時間などを含みます。

デフォルトの場所:

# Ubuntu/Debian
/var/log/nginx/access.log

CentOS/RHEL

/var/log/nginx/access.log

macOS (Homebrew)

/usr/local/var/log/nginx/access.log

基本設定:

http {
# HTTPコンテキスト全体のアクセスログ
access_log /var/log/nginx/access.log;

server {
    listen 80;
    server_name example.com;
    
    # バーチャルホスト専用のアクセスログ
    access_log /var/log/nginx/example.com.access.log;
    
    location / {
        root /var/www/html;
    }
    
    # 特定ロケーションのアクセスログを無効化
    location /health-check {
        access_log off;
        return 200 "OK\n";
    }
}

}

デフォルトフォーマット(combined):

192.168.1.100 - - [03/Dec/2024:10:30:45 +0700] "GET /index.html HTTP/1.1" 200 1234 "https://google.com" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"

フィールドの説明:

  • 192.168.1.100 - クライアントのIPアドレス
  • - - リモートユーザー(認証なしの場合は通常-)
  • - - 認証済みユーザー
  • [03/Dec/2024:10:30:45 +0700] - タイムスタンプ
  • "GET /index.html HTTP/1.1" - リクエストメソッド、URI、HTTPバージョン
  • 200 - HTTPステータスコード
  • 1234 - レスポンスボディサイズ(バイト)
  • "https://google.com" - リファラー
  • "Mozilla/5.0..." - ユーザーエージェント

1.2. エラーログ

エラーログはNginxからのエラー、警告、デバッグ情報を記録します。

デフォルトの場所:

/var/log/nginx/error.log

ログレベル(詳細度の低い順):

  1. emerg - 緊急:システム使用不能
  2. alert - アラート:即座に対応が必要
  3. crit - 致命的な状態
  4. error - エラー状態
  5. warn - 警告状態
  6. notice - 通常だが重要
  7. info - 情報
  8. debug - デバッグメッセージ

設定:

# グローバルエラーログ
error_log /var/log/nginx/error.log warn;

http { # HTTPレベルのエラーログ error_log /var/log/nginx/http-error.log error;

server {
    listen 80;
    server_name example.com;
    
    # サーバーレベルのエラーログ
    error_log /var/log/nginx/example.com.error.log error;
    
    # トラブルシューティング用デバッグログ
    error_log /var/log/nginx/debug.log debug;
}

}

エラーログの例:

2024/12/03 10:30:45 [error] 1234#1234: *1 open() "/var/www/html/notfound.html" failed (2: No such file or directory), client: 192.168.1.100, server: example.com, request: "GET /notfound.html HTTP/1.1", host: "example.com"

2024/12/03 10:31:20 [warn] 1234#1234: *2 upstream server temporarily disabled while connecting to upstream, client: 192.168.1.101, server: api.example.com, request: "GET /api/users HTTP/1.1", upstream: "http://192.168.1.200:3000/api/users"

2024/12/03 10:32:05 [crit] 1234#1234: malloc() 8192 bytes failed (12: Cannot allocate memory)

1.3. リアルタイムでのログ表示と監視

# アクセスログを表示
sudo tail -f /var/log/nginx/access.log

エラーログを表示

sudo tail -f /var/log/nginx/error.log

最後の100行を表示

sudo tail -n 100 /var/log/nginx/access.log

両方のログを同時に表示

sudo tail -f /var/log/nginx/access.log /var/log/nginx/error.log

ログをフィルタリング

sudo tail -f /var/log/nginx/access.log | grep "404" sudo tail -f /var/log/nginx/access.log | grep "192.168.1.100"

lessでログを表示(スクロール可)

sudo less +F /var/log/nginx/access.log

1.4. 基本的なログ分析

総リクエスト数を数える:

# 総リクエスト数
wc -l /var/log/nginx/access.log

過去1時間のリクエスト

sudo awk -v date="$(date -d '1 hour ago' '+%d/%b/%Y:%H')" '$4 > "["date' /var/log/nginx/access.log | wc -l

上位10 IP:

sudo awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -10

上位10アクセスURL:

sudo awk '{print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -10

HTTPステータスコードの集計:

sudo awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c | sort -rn

上位ユーザーエージェント:

sudo awk -F'"' '{print $6}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -10

時間別リクエスト数:

sudo awk '{print $4}' /var/log/nginx/access.log | cut -d: -f1-2 | sort | uniq -c

2. カスタムログフォーマット

Nginxでは必要な情報だけを収集するカスタムログフォーマットを作成できます。

2.1. 基本ログフォーマット

フォーマットの定義:

http {
# デフォルトフォーマット(combined)
log_format combined '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';

# シンプルなフォーマット
log_format simple '$remote_addr - $request - $status';

# 詳細フォーマット
log_format detailed '$remote_addr - $remote_user [$time_local] '
                    '"$request" $status $body_bytes_sent '
                    '"$http_referer" "$http_user_agent" '
                    'rt=$request_time uct="$upstream_connect_time" '
                    'uht="$upstream_header_time" urt="$upstream_response_time"';

server {
    listen 80;
    
    # カスタムフォーマットを使用
    access_log /var/log/nginx/access.log detailed;
}

}

2.2. よく使う変数

クライアント情報:

$remote_addr          # クライアントIP
$remote_user          # HTTP認証ユーザー
$http_x_forwarded_for # プロキシ/CDN経由の実IPアドレス

リクエスト情報:

$time_local           # ローカル時刻
$time_iso8601         # ISO 8601形式の時刻
$request              # フルリクエストライン
$request_method       # GET、POST など
$request_uri          # 引数付きのリクエストURI
$uri                  # 現在のURI
$args                 # クエリ文字列の引数
$query_string         # $argsと同じ
$scheme               # httpまたはhttps
$server_protocol      # HTTP/1.1、HTTP/2.0
$host                 # Hostヘッダー
$server_name          # サーバー名

レスポンス情報:

$status               # HTTPステータスコード
$body_bytes_sent      # レスポンスボディサイズ
$bytes_sent           # 送信バイト総数(ヘッダー + ボディ)
$request_length       # リクエスト長(ヘッダー含む)

タイミング情報:

$request_time         # リクエスト処理時間(秒)
$upstream_response_time    # バックエンドのレスポンス時間
$upstream_connect_time     # アップストリームへの接続時間
$upstream_header_time      # アップストリームのヘッダー受信時間

アップストリーム情報:

$upstream_addr             # アップストリームサーバーアドレス
$upstream_status           # アップストリームのレスポンスステータス
$upstream_cache_status     # キャッシュステータス(HIT、MISSなど)

ヘッダー:

$http_user_agent      # User-Agentヘッダー
$http_referer         # Refererヘッダー
$http_cookie          # Cookieヘッダー
$http_<header_name>   # 任意のHTTPヘッダー(小文字とアンダースコア)

2.3. 実用的なログフォーマット例

パフォーマンス監視フォーマット:

log_format performance '$remote_addr - [$time_local] "$request" '
'$status $body_bytes_sent '
'rt=$request_time '
'uct=$upstream_connect_time '
'uht=$upstream_header_time '
'urt=$upstream_response_time';

server { listen 80; access_log /var/log/nginx/performance.log performance; }

出力:

192.168.1.100 - [03/Dec/2024:10:30:45 +0700] "GET /api/users HTTP/1.1" 200 1234 rt=0.125 uct=0.005 uht=0.050 urt=0.120

JSONフォーマット(解析しやすい):

log_format json_combined escape=json
'{'
'"time_local":"$time_local",'
'"remote_addr":"$remote_addr",'
'"request":"$request",'
'"status":$status,'
'"body_bytes_sent":$body_bytes_sent,'
'"request_time":$request_time,'
'"http_referer":"$http_referer",'
'"http_user_agent":"$http_user_agent"'
'}';

server { listen 80; access_log /var/log/nginx/access.json json_combined; }

出力:

{"time_local":"03/Dec/2024:10:30:45 +0700","remote_addr":"192.168.1.100","request":"GET /index.html HTTP/1.1","status":200,"body_bytes_sent":1234,"request_time":0.005,"http_referer":"https://google.com","http_user_agent":"Mozilla/5.0"}

セキュリティ監視フォーマット:

log_format security '$remote_addr - [$time_local] '
'"$request" $status '
'"$http_user_agent" '
'"$http_x_forwarded_for" '
'host=$host '
'args=$args';

server { listen 80; access_log /var/log/nginx/security.log security; }

CDN/プロキシフォーマット:

log_format cdn '$http_x_forwarded_for - $remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'cache=$upstream_cache_status';

server { listen 80; access_log /var/log/nginx/cdn.log cdn; }

2.4. 条件付きロギング

条件を満たす場合のみログ記録:

http {
# 条件確認用マップを定義
map $status $loggable {
~^[23]  0;  # 2xxと3xxはログ不要
default 1;  # それ以外はすべてログ
}

server {
    listen 80;
    
    # $loggable = 1の場合のみログ記録
    access_log /var/log/nginx/errors-only.log combined if=$loggable;
}

}

静的ファイルをログ対象外にする:

map $request_uri $log_static {
~*.(jpg|jpeg|png|gif|ico|css|js)$ 0;
default 1;
}

server { listen 80; access_log /var/log/nginx/access.log combined if=$log_static; }

ヘルスチェックをログ対象外にする:

map $request_uri $log_health {
~^/health$ 0;
~^/ping$ 0;
default 1;
}

server { listen 80; access_log /var/log/nginx/access.log combined if=$log_health; }

ボットをログ対象外にする:

map $http_user_agent $log_bots {
~bot 0;
~crawler 0;
~*spider 0;
default 1;
}

server { listen 80; access_log /var/log/nginx/access.log combined if=$log_bots; }

2.5. 複数のアクセスログ

server {
listen 80;
server_name example.com;

# すべてのリクエストをログ
access_log /var/log/nginx/all.log combined;

# エラーのみログ
access_log /var/log/nginx/errors.log combined if=$loggable;

# パフォーマンスログ
access_log /var/log/nginx/performance.log performance;

# 処理用JSONログ
access_log /var/log/nginx/json.log json_combined;

}


3. Logrotateによるログローテーション

ログファイルは非常に速く成長します。ログローテーションにより古いログを自動的に圧縮・削除してディスク容量を管理できます。

3.1. Logrotateの基本

デフォルトの設定ファイル:

# Ubuntu/Debian
/etc/logrotate.d/nginx

CentOS/RHEL

/etc/logrotate.d/nginx

デフォルトの内容:

/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
postrotate
if [ -f /var/run/nginx.pid ]; then
kill -USR1 cat /var/run/nginx.pid
fi
endscript
}

ディレクティブの説明:

  • daily - 毎日ローテーション
  • missingok - ログファイルがなくてもエラーにしない
  • rotate 14 - バックアップを14個保持
  • compress - 古いログをgzipで圧縮
  • delaycompress - 次のローテーションまで圧縮を遅らせる
  • notifempty - ファイルが空の場合はローテーションしない
  • create 0640 www-data adm - 指定したパーミッションで新しいファイルを作成
  • sharedscripts - すべてのログに対してpostrotateスクリプトを1回実行
  • postrotate/endscript - ローテーション後に実行するスクリプト

3.2. カスタムLogrotate設定

時間単位でローテーション(高トラフィックサイト向け):

sudo nano /etc/logrotate.d/nginx-hourly

内容:

/var/log/nginx/high-traffic.log { hourly rotate 168 # 7日 × 24時間 compress delaycompress notifempty create 0640 www-data adm dateext dateformat -%Y%m%d-%H sharedscripts postrotate if [ -f /var/run/nginx.pid ]; then kill -USR1 cat /var/run/nginx.pid fi endscript }

サイズでローテーション:

/var/log/nginx/.log {
size 100M           # 100MBに達したらローテーション
rotate 10
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
postrotate
if [ -f /var/run/nginx.pid ]; then
kill -USR1 cat /var/run/nginx.pid
fi
endscript
}

カスタム命名でローテーション:

/var/log/nginx/.log {
daily
rotate 30
compress
delaycompress
notifempty
create 0640 www-data adm
dateext
dateformat -.%Y-%m-%d
extension .log
sharedscripts
postrotate
if [ -f /var/run/nginx.pid ]; then
kill -USR1 cat /var/run/nginx.pid
fi
endscript
}

出力: access.log-2024-12-03.log.gz

ログ別に分けてローテーション:

# パフォーマンスログ - 長期保存
/var/log/nginx/performance.log {
daily
rotate 90           # 3ヶ月
compress
delaycompress
notifempty
create 0640 www-data adm
}

エラーログ - 非常に長期保存

/var/log/nginx/error.log { weekly rotate 52 # 1年 compress delaycompress notifempty create 0640 www-data adm }

アクセスログ - 早めにローテーション

/var/log/nginx/access.log { daily rotate 7 # 1週間 compress delaycompress notifempty create 0640 www-data adm }

3.3. ローテーションのテストと強制実行

# 設定をテスト(ドライラン)
sudo logrotate -d /etc/logrotate.d/nginx

強制ローテーション(即時実行)

sudo logrotate -f /etc/logrotate.d/nginx

ステータスを確認

sudo cat /var/lib/logrotate/status

手動ローテーション(logrotateなし)

sudo mv /var/log/nginx/access.log /var/log/nginx/access.log.1 sudo nginx -s reopen sudo gzip /var/log/nginx/access.log.1

3.4. Logrotateのトラブルシューティング

logrotateが動作しているか確認:

# cronジョブを確認
ls -la /etc/cron.daily/logrotate

logrotateステータスを確認

sudo cat /var/lib/logrotate/status | grep nginx

詳細付きで手動実行

sudo logrotate -v /etc/logrotate.d/nginx

よくあるエラー:

# エラー: Permission denied

修正: 所有権を確認

ls -la /var/log/nginx/ sudo chown www-data:adm /var/log/nginx/*.log

エラー: Nginxがログを再オープンしない

修正: PIDファイルを確認

ls -la /var/run/nginx.pid sudo systemctl restart nginx

エラー: ログが圧縮されない

修正: gzipがインストールされているか確認

which gzip sudo apt install gzip


4. モニタリングの基本メトリクス

4.1. 毎秒リクエスト数(RPS)

RPSを計算するスクリプト:

#!/bin/bash

rps.sh - RPSを計算

LOG_FILE="/var/log/nginx/access.log" INTERVAL=60 # 秒

while true; do START_COUNT=$(wc -l < "$LOG_FILE") sleep $INTERVAL END_COUNT=$(wc -l < "$LOG_FILE")

REQUESTS=$((END_COUNT - START_COUNT))
RPS=$(echo "scale=2; $REQUESTS / $INTERVAL" | bc)

echo "$(date '+%Y-%m-%d %H:%M:%S') - RPS: $RPS"

done

スクリプトの実行:

chmod +x rps.sh
./rps.sh

4.2. レスポンス時間分析

レスポンス時間を分析するスクリプト:

#!/bin/bash

response_time.sh - レスポンス時間を分析

LOG_FILE="/var/log/nginx/access.log"

echo "レスポンス時間の統計:" echo "===================="

request_timeを抽出(ログに記録されている前提)

awk '{print $NF}' "$LOG_FILE" |
awk '{ sum += $1; count++; if ($1 > max) max = $1; if (min == 0 || $1 < min) min = $1; } END { print "平均: " sum/count " 秒"; print "最小: " min " 秒"; print "最大: " max " 秒"; }'

4.3. ステータスコードの分布

#!/bin/bash

status_codes.sh - HTTPステータスコードを集計

LOG_FILE="/var/log/nginx/access.log"

echo "HTTPステータスコードの分布:" echo "============================"

awk '{print $9}' "$LOG_FILE" | sort | uniq -c | sort -rn |
while read count code; do percentage=$(echo "scale=2; ($count * 100) / $(wc -l < $LOG_FILE)" | bc) printf "%3s: %6d リクエスト (%5.2f%%)\n" "$code" "$count" "$percentage" done

4.4. 時間別トラフィック

#!/bin/bash

traffic_by_hour.sh - 時間別トラフィックを分析

LOG_FILE="/var/log/nginx/access.log"

echo "時間別トラフィック:" echo "=================="

awk '{print $4}' "$LOG_FILE" | cut -d: -f2 | sort | uniq -c |
while read count hour; do printf "時 %02d: %6d リクエスト\n" "$hour" "$count" done

4.5. 上位クライアント(IPアドレス)

#!/bin/bash

top_clients.sh - リクエスト数の多いクライアントを検索

LOG_FILE="/var/log/nginx/access.log" TOP_N=10

echo "上位 $TOP_N クライアント:" echo "========================="

awk '{print $1}' "$LOG_FILE" | sort | uniq -c | sort -rn | head -n $TOP_N |
while read count ip; do printf "%15s: %6d リクエスト\n" "$ip" "$count" done

4.6. 帯域幅の使用量

#!/bin/bash

bandwidth.sh - 帯域幅の使用量を計算

LOG_FILE="/var/log/nginx/access.log"

echo "帯域幅統計:" echo "==========="

$body_bytes_sentが10番目のフィールドにある前提

awk '{sum += $10} END { gb = sum / 1024 / 1024 / 1024; mb = sum / 1024 / 1024; kb = sum / 1024; printf "合計: %.2f GB (%.2f MB, %.2f KB)\n", gb, mb, kb; }' "$LOG_FILE"

4.7. リアルタイムダッシュボードスクリプト

#!/bin/bash

dashboard.sh - Nginxリアルタイム監視ダッシュボード

LOG_FILE="/var/log/nginx/access.log"

while true; do clear echo "=======================================" echo " NGINX 監視ダッシュボード" echo "=======================================" echo "時刻: $(date '+%Y-%m-%d %H:%M:%S')" echo

# 総リクエスト数
TOTAL=$(wc -l &lt; "$LOG_FILE")
echo "総リクエスト数: $TOTAL"
echo

echo "直近 ~1000 リクエスト"
echo

# ステータスコード(直近1000件)
echo "ステータスコード(直近):"
tail -n 1000 "$LOG_FILE" | awk '{print $9}' | sort | uniq -c | sort -rn
echo

# 上位5 IP(直近)
echo "上位5 IP(直近):"
tail -n 1000 "$LOG_FILE" | awk '{print $1}' | sort | uniq -c | sort -rn | head -5
echo

# 上位5 URL(直近)
echo "上位5 URL(直近):"
tail -n 1000 "$LOG_FILE" | awk '{print $7}' | sort | uniq -c | sort -rn | head -5

sleep 5

done

ダッシュボードの実行:

chmod +x dashboard.sh
./dashboard.sh

4.8. 問題発生時のアラート送信

#!/bin/bash

alert.sh - エラー率が高い場合にアラートを送信

LOG_FILE="/var/log/nginx/access.log" ERROR_THRESHOLD=10 # 5xxエラーの割合(%) EMAIL="[email protected]"

直近100件を集計

TOTAL=$(tail -n 100 "$LOG_FILE" | wc -l) ERRORS=$(tail -n 100 "$LOG_FILE" | awk '{print $9}' | grep "^5" | wc -l)

ERROR_RATE=$(echo "scale=2; ($ERRORS * 100) / $TOTAL" | bc)

if (( $(echo "$ERROR_RATE > $ERROR_THRESHOLD" | bc -l) )); then MESSAGE="アラート:高いエラー率を検知!5xxエラーが${ERROR_RATE}%に達しています" echo "$MESSAGE" | mail -s "Nginx アラート" "$EMAIL" echo "$MESSAGE" fi

4.9. モニタリングツールとの連携

Prometheus用メトリクスのエクスポート:

# nginx-prometheus-exporterをインストール
wget https://github.com/nginxinc/nginx-prometheus-exporter/releases/download/v0.11.0/nginx-prometheus-exporter_0.11.0_linux_amd64.tar.gz
tar xzf nginx-prometheus-exporter_0.11.0_linux_amd64.tar.gz
sudo mv nginx-prometheus-exporter /usr/local/bin/

エクスポーターを起動

nginx-prometheus-exporter -nginx.scrape-uri=http://localhost:8080/stub_status

Nginx stub_statusの設定:

server {
listen 8080;
server_name localhost;

location /stub_status {
    stub_status;
    access_log off;
    allow 127.0.0.1;
    deny all;
}

}


5. 実践演習

演習1:カスタムログフォーマット

  1. 以下を含むtimingというカスタムログフォーマットを作成する:
    • リモートアドレス
    • リクエスト
    • ステータス
    • リクエスト時間
    • アップストリームのレスポンス時間
  2. このフォーマットをバーチャルホストに適用する
  3. トラフィックを生成してログを確認する

演習2:JSONロギング

  1. JSONログフォーマットを作成する
  2. JSONでログ出力するようNginxを設定する
  3. jqでJSONログを解析する:
cat /var/log/nginx/access.json | jq '.status'
cat /var/log/nginx/access.json | jq 'select(.status >= 400)'

演習3:ログローテーション

  1. 10MBでローテーションするカスタムlogrotate設定を作成する
  2. logrotate -dでテストする
  3. ローテーションを強制実行して確認する

演習4:トラフィック分析

  1. abで1000件のリクエストを生成する:
ab -n 1000 -c 10 http://localhost/
  1. ログを分析して以下を調べる:
    • 総リクエスト数
    • 平均レスポンス時間
    • ステータスコードの分布
    • 上位URL

演習5:リアルタイムモニタリング

  1. ダッシュボードスクリプトを設定する
  2. 以下を追加するよう修正する:
    • エラー率(%)
    • 帯域幅の使用量
    • 最も遅いリクエスト

演習6:条件付きロギング

  1. 以下をログ対象外に設定する:
    • 静的ファイル(.css、.js、.jpg、.png)
    • ヘルスチェックエンドポイント(/health)
    • ボットのトラフィック
  2. これらのリクエストがログに現れないことを確認する

6. ログを使ったトラブルシューティング

6.1. 404エラーのデバッグ

# すべての404を検索
grep " 404 " /var/log/nginx/access.log

404を引き起こしている上位URL

grep " 404 " /var/log/nginx/access.log | awk '{print $7}' | sort | uniq -c | sort -rn | head -10

特定IPからの404

grep "192.168.1.100" /var/log/nginx/access.log | grep " 404 "

6.2. 500エラーのデバッグ

# 5xxエラーを検索
grep " 50[0-9] " /var/log/nginx/access.log

詳細はエラーログを確認

sudo tail -100 /var/log/nginx/error.log | grep "error"

時間別の5xxエラー

grep " 50[0-9] " /var/log/nginx/access.log | awk '{print $4}' | cut -d: -f1-2 | uniq -c

6.3. 遅いリクエストのデバッグ

# 1秒以上のリクエストを検索(request_timeがログされている前提)
awk '$NF > 1.0' /var/log/nginx/access.log

上位10件の最も遅いリクエスト

awk '{print $NF, $7}' /var/log/nginx/access.log | sort -rn | head -10

6.4. 高トラフィックのデバッグ

# 毎分のリクエスト数
awk '{print $4}' /var/log/nginx/access.log | cut -d: -f1-3 | uniq -c

トラフィックスパイクを特定

awk '{print $4}' /var/log/nginx/access.log | cut -d: -f1-3 | uniq -c | awk '$1 > 1000'

6.5. セキュリティ問題のデバッグ

# SQLインジェクション試行を検索
grep -i "select.*from|union.*select" /var/log/nginx/access.log

パストラバーサル試行を検索

grep ".." /var/log/nginx/access.log

不審なユーザーエージェント

grep -i "sqlmap|nikto|nmap" /var/log/nginx/access.log


7. ベストプラクティス

7.1. ログ管理

  1. バーチャルホスト別にログを分ける:
server {
server_name site1.com;
access_log /var/log/nginx/site1.access.log;
error_log /var/log/nginx/site1.error.log;
}
  1. 適切なログレベルを使用する:
# 本番: errorまたはwarn
error_log /var/log/nginx/error.log warn;

開発: infoまたはdebug

error_log /var/log/nginx/error.log debug;

  1. 過剰にログを記録しない:
# 静的ファイルは無効化
location ~* .(jpg|jpeg|png|gif|ico|css|js)$ {
access_log off;
}

ヘルスチェックは無効化

location /health { access_log off; return 200; }

7.2. パフォーマンス

  1. ログをバッファリングする:
access_log /var/log/nginx/access.log combined buffer=32k;
  1. 非同期ロギング(Nginx 1.7.11+):
access_log /var/log/nginx/access.log combined buffer=32k flush=5s;

7.3. セキュリティ

  1. ログファイルを保護する:
sudo chmod 640 /var/log/nginx/.log
sudo chown www-data:adm /var/log/nginx/.log
  1. 定期的にローテーションする:
# 高トラフィックサイトは毎日ローテーション

低トラフィックサイトは毎週ローテーション

  1. 監視とアラートを設定する:
# エラー率の監視を設定する

異常なスパイクでアラートを送信する


まとめ

この課では以下を学びました:

  • ✅ アクセスログとエラーログ
  • ✅ カスタムログフォーマットと変数
  • ✅ logrotateによるログローテーション
  • ✅ ログ分析とメトリクス
  • ✅ ログを使ったトラブルシューティング
  • ✅ ロギングのベストプラクティス

次の課: リバースプロキシを探ります——Nginxをバックエンドアプリケーションのリバースプロキシとしてどう活用するかを学びます。