🐺

アクセスログとNew Relic APMを駆使してCPU負荷のボトルネックを見つけてみた

に公開

本記事では、Nginxのアクセスログを解析し、Metabaseで可視化することと、newRelicを駆使したWebアプリケーションのパフォーマンス問題を特定する方法を紹介します。

📊 背景:なぜログ解析が必要なのか

運用歴の長いサービスでは、担当者の入れ替わりや機能追加の積み重ねによって、傾向監視等で見てない場合に、どのエンドポイントが実際に使われ、どんなトランザクションが走っているのかを把握しづらくなります。その結果、サービス全体の“健康状態”が見えにくくなり、潜在的な問題が埋もれがちです。
そこで、Nginxのアクセスログを定量的に分析し、Metabaseで可視化することで、利用状況を健康診断のように整理できます。さらに newRelic を用いたAPM分析を併用することで、負荷や遅延の原因となるボトルネックも明らかになります。これにより、次のようなポイントを把握しやすくなります:

  • 特定のエンドポイントへの異常なアクセス集中
  • レスポンスが遅いAPIの特定
  • 時間帯別のアクセスパターンの把握
  • 不要な古いエンドポイントの発見

📝 Step 1: サーバーからログファイルを取得

それでは、ローカル環境で簡易的に解析した方法を書きいます。
まず、本番環境のログサーバーからログファイルをローカルにダウンロードします。
※ここのサーバーは実際のディレクトリ構造は適当なものに変えてほしい。

scp your-log-server:/var/log/nginx/access.log.20251007.gz ~/Desktop

🐍 Step 2: Pythonでログを解析

Nginxのアクセスログは通常、固定フォーマットで出力されます。Pythonスクリプトを使って、必要な情報(タイムスタンプ、ホスト名、パス)を抽出し、CSV形式で日付ごとに分割します。

まず、Pythonがインストールされているか確認:

python3 --version

次に、claudeにpythonで適当に作っていただいたログ解析スクリプトを作成します:

vi log_parser.py
ログ解析スクリプト(log_parser.py)
import re
import csv
import sys
import os
from datetime import datetime
from collections import defaultdict
import tempfile
import shutil

def parse_log_line(line):
    if not line.strip():
        return None

    # Regular expressions for error log format
    error_request_pattern = r'request: "([A-Z]+) ([^\\s]+) HTTP/[\\d\\.]+"'

    # Regular expressions for access log format
    access_path_pattern = r'path:([^\\s]+)'

    # Common patterns for both formats
    hostname_pattern = r'hostname:([^\\s]+)'
    time_pattern = r'time:(\\d{4}/\\d{2}/\\d{2} \\d{2}:\\d{2}:\\d{2} [+-]\\d{4})'

    path = None

    # Try error log format first
    error_request_match = re.search(error_request_pattern, line)
    if error_request_match:
        method = error_request_match.group(1)
        full_path = error_request_match.group(2)
        # Remove query string if present
        path = full_path.split('?')[0]
    else:
        # Try access log format
        access_path_match = re.search(access_path_pattern, line)
        if access_path_match:
            full_path = access_path_match.group(1)
            # Remove query string if present
            path = full_path.split('?')[0]

    hostname_match = re.search(hostname_pattern, line)
    time_match = re.search(time_pattern, line)

    # Skip line if no path found
    if not path or not hostname_match or not time_match:
        print(f"Skipping this line: {line}")

    # Extract hostname
    hostname = hostname_match.group(1)

    # Extract timestamp
    timestamp = time_match.group(1)

    return {
        'timestamp': timestamp,
        'hostname': hostname,
        'path': path
    }

def get_date_key(timestamp_str):
    try:
        # Parse timestamp (format: 2025/06/27 00:00:00 +0900)
        dt = datetime.strptime(timestamp_str.split(' +')[0].split(' -')[0], '%Y/%m/%d %H:%M:%S')
        date_str = dt.strftime('%Y%m%d')  # 20250627
        return date_str
    except:
        return None

def process_log_file(file_path, output_dir, file_count, total_files):
    if not os.path.exists(file_path):
        print(f"✗ File not found: {file_path}")
        return 0

    print(f"\\n[{file_count}/{total_files}] Processing {file_path}...")

    # Dictionary to track which files we've written to
    written_files = set()
    fieldnames = ['timestamp', 'hostname', 'path']

    try:
        entries_found = 0
        entries_by_date = defaultdict(int)

        with open(file_path, 'r', encoding='utf-8') as f:
            # Process file line by line
            for line_num, line in enumerate(f, 1):
                if line_num % 10000 == 0:
                    print(f"  Processing line {line_num:,}...", end='\\r')

                parsed_data = parse_log_line(line)
                if parsed_data and parsed_data['timestamp']:
                    date_str = get_date_key(parsed_data['timestamp'])

                    if date_str:
                        # Create daily file: YYYYMMDD.csv.tmp (temporary unsorted)
                        daily_file = os.path.join(output_dir, f"{date_str}.csv.tmp")

                        # Check if this is the first write to this file
                        first_write = daily_file not in written_files
                        written_files.add(daily_file)

                        # Write data (append mode)
                        with open(daily_file, 'a', newline='', encoding='utf-8') as csvfile:
                            writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

                            # Write header only on first write to a new file
                            if first_write and os.path.getsize(daily_file) == 0:
                                writer.writeheader()

                            writer.writerow(parsed_data)

                        entries_found += 1
                        entries_by_date[date_str] += 1

        print(f"\\n  ✓ Found {entries_found:,} entries" + " " * 30)
        return entries_found, entries_by_date

    except Exception as e:
        print(f"\\n  ✗ Error: {str(e)}")
        return 0, {}

def sort_daily_file(temp_file_path, final_file_path):
    print(f"  Sorting {os.path.basename(final_file_path)}...", end='')

    try:
        # Read all data from temp file
        rows = []
        with open(temp_file_path, 'r', encoding='utf-8') as f:
            reader = csv.DictReader(f)
            rows = list(reader)

        # Sort by timestamp
        rows.sort(key=lambda x: x['timestamp'])

        # Write sorted data to final file
        with open(final_file_path, 'w', newline='', encoding='utf-8') as f:
            writer = csv.DictWriter(f, fieldnames=['timestamp', 'hostname', 'path'])
            writer.writeheader()
            writer.writerows(rows)

        # Remove temp file
        os.remove(temp_file_path)

        print(f" ✓ ({len(rows):,} entries)")
        return True

    except Exception as e:
        print(f" ✗ Error: {str(e)}")
        return False

def sort_all_daily_files(output_dir, all_entries_by_date):
    """
    Sort all temporary daily files by timestamp
    """
    print("\\nSorting daily files by timestamp...")

    sorted_count = 0
    error_count = 0

    for date_str in sorted(all_entries_by_date.keys()):
        temp_file = os.path.join(output_dir, f"{date_str}.csv.tmp")
        final_file = os.path.join(output_dir, f"{date_str}.csv")

        if os.path.exists(temp_file):
            if sort_daily_file(temp_file, final_file):
                sorted_count += 1
            else:
                error_count += 1

    print(f"\\n✓ Sorted {sorted_count} daily files")
    if error_count > 0:
        print(f"✗ Failed to sort {error_count} files")

def create_index_file(output_dir, all_entries_by_date):
    """
    Create an index file listing all generated CSV files with entry counts
    """
    index_file = os.path.join(output_dir, 'index.txt')

    with open(index_file, 'w', encoding='utf-8') as f:
        f.write("Daily Log Files Index\\n")
        f.write("=" * 50 + "\\n\\n")
        f.write("Format: logs_daily/YYYYMMDD.csv\\n")
        f.write("Note: All files are sorted by timestamp\\n\\n")

        # Write summary by date
        total_all_days = 0
        for date_str in sorted(all_entries_by_date.keys()):
            year = date_str[:4]
            month = date_str[4:6]
            day = date_str[6:8]
            count = all_entries_by_date[date_str]
            total_all_days += count

            f.write(f"{year}-{month}-{day}: {count:,} entries\\n")

        f.write(f"\\nTotal entries: {total_all_days:,}\\n")

    print(f"\\n✓ Created index file: {index_file}")

def main():
    """
    Main function to handle command line arguments and process files
    """
    if len(sys.argv) < 2:
        print("Usage: python log_parser_daily.py <log_file1.txt> [log_file2.txt] [log_file3.txt] ...")
        print("\\nExample:")
        print("  python log_parser_daily.py server1.txt server2.txt server3.txt")
        print("\\nYou can also use wildcards:")
        print("  python log_parser_daily.py logs/*.txt")
        print("\\nFeatures:")
        print("  - Memory-efficient: writes line by line")
        print("  - Organized output: one CSV file per date")
        print("  - Sorted by timestamp: each daily file is chronologically ordered")
        print("\\nOutput structure:")
        print("  logs_daily/")
        print("    ├── 20250627.csv  (all entries for June 27, 2025)")
        print("    ├── 20250628.csv  (all entries for June 28, 2025)")
        print("    ├── ...")
        print("    └── index.txt     (summary of all files)")
        return

    # Get file paths from command line arguments
    file_paths = sys.argv[1:]
    output_dir = 'logs_daily_god'

    print(f"Found {len(file_paths)} file(s) to process")
    print(f"Output directory: {output_dir}/\\n")

    # Create output directory
    os.makedirs(output_dir, exist_ok=True)

    total_entries = 0
    all_entries_by_date = defaultdict(int)

    # Process each file
    for idx, file_path in enumerate(file_paths, 1):
        entries, entries_by_date = process_log_file(file_path, output_dir, idx, len(file_paths))
        total_entries += entries

        # Aggregate daily counts
        for date_str, count in entries_by_date.items():
            all_entries_by_date[date_str] += count

    if total_entries > 0:
        print(f"\\n{'='*60}")
        print(f"✓ Processed {total_entries:,} log entries from {len(file_paths)} file(s)")

        # Sort all daily files
        sort_all_daily_files(output_dir, all_entries_by_date)

        # Create index file
        create_index_file(output_dir, all_entries_by_date)

        # Show summary
        print("\\nSummary:")
        unique_days = len(all_entries_by_date)
        print(f"  - {unique_days} daily files (all sorted by timestamp)")
        print(f"  - {total_entries:,} total entries")

        # Show sample file paths
        sample_files = list(all_entries_by_date.keys())[:5]
        if sample_files:
            print("\\nSample files created:")
            for date_str in sample_files:
                file_path = f"{output_dir}/{date_str}.csv"
                count = all_entries_by_date[date_str]
                year = date_str[:4]
                month = date_str[4:6]
                day = date_str[6:8]
                print(f"  - {file_path} ({year}-{month}-{day}: {count:,} entries)")
            if len(all_entries_by_date) > 5:
                print(f"  - ... and {len(all_entries_by_date) - 5} more files")

        print(f"\\n✓ All files ready in: {output_dir}/")
    else:
        print("\\nNo valid log entries found in the provided files.")

if __name__ == "__main__":
    main()

スクリプトの内容は上記のlog_parser.pyを参照してください。このスクリプトは以下の処理を行います:

  • Nginxのログフォーマットを正規表現で解析
  • タイムスタンプ、ホスト名、リクエストパスを抽出
  • 日付ごとにCSVファイルを生成
  • タイムスタンプでソート済みのデータを出力

スクリプトを実行:

python3 log_parser.py logs.access.log.20251007.log

実行が完了すると分析に必要なデータのみで構成されたCSVファイルが生成されます。

🐳 Step 3: Docker ComposeでMetabase環境を構築

Metabaseは、SQLデータベースに接続してビジュアルなダッシュボードを作成できるOSSのBIツールです。Docker Composeを使って簡単に環境を構築できます。
https://www.metabase.com/docs/latest/installation-and-operation/running-metabase-on-docker#example-docker-compose-yaml-file
以下の内容を記述します(公式ドキュメントを参考):

services:
  metabase:
    image: metabase/metabase:latest
    container_name: metabase
    hostname: metabase
    volumes:
      - /dev/urandom:/dev/random:ro
    ports:
      - 3000:3000
    environment:
      MB_DB_TYPE: postgres
      MB_DB_DBNAME: metabaseappdb
      MB_DB_PORT: 5432
      MB_DB_USER: metabase
      MB_DB_PASS: mysecretpassword
      MB_DB_HOST: postgres
    networks:
      - metanet1
    healthcheck:
      test: curl --fail -I http://localhost:3000/api/health || exit 1
      interval: 15s
      timeout: 5s
      retries: 5
  postgres:
    image: postgres:latest
    container_name: postgres
    hostname: postgres
    environment:
      POSTGRES_USER: metabase
      POSTGRES_DB: metabaseappdb
      POSTGRES_PASSWORD: mysecretpassword
    networks:
      - metanet1
networks:
  metanet1:
    driver: bridge

Dockerデーモンを起動し、コンテナを立ち上げます:

docker compose up -d

💾 Step 4: PostgreSQLにログデータをインポート

生成されたCSVファイルをPostgreSQLコンテナにコピーします:

docker compose cp logs.access.log.20251007.log postgres:/log.csv

PostgreSQLコンテナに接続:

docker compose exec postgres psql -U metabase metabaseappdb

テーブルを作成し、CSVデータをインポートします:

CREATE TABLE access_logs (
    id SERIAL PRIMARY KEY,
    event_time TIMESTAMPTZ NOT NULL,
    hostname TEXT NOT NULL,
    path TEXT NOT NULL
);

COPY access_logs (event_time, hostname, path)
FROM '/log.csv'
WITH (
    FORMAT csv,
    HEADER true,
    DELIMITER ','
);

📈 Step 5: Metabaseで可視化

ブラウザでhttp://localhost:3000/にアクセスすると、Metabaseの初期設定画面が表示されます。

  • アカウント情報を入力して登録
  • データベース接続設定で、先ほど作成したPostgreSQLデータベースを選択
  • データベースにaccess_logsテーブルが表示されるので選択

あとは諸々時系列グラフやテーブルで結果を確認できます。「Visualize」ボタンをクリックすると、様々なチャートタイプを選択できます。今回の例を以下に示します

アクセスログから見える傾向
グラフを見ると、以下のことがわかります:

  • /test/path/B(青線)が圧倒的にトラフィックが多く、ピーク時には6,000リクエスト/分近くに達している
  • /test/path/A(水色)が次に多く、1,000〜1,500リクエスト/分程度で推移
  • その他のエンドポイントは比較的安定しており、数百リクエスト/分以下

しかし、これだけではこのトラフィックがサーバーにどの程度の負荷を与えているのかがわかりません。そこで、APMを用いてMetabaseで特定したトランザクションがパフォーマンスにどの程度影響しているのかを調査しました

📊 NewRelicとアクセスログとの組み合わせ

Metabaseでの詳細分析に加えて、New RelicのAPM機能を使うとさらに深い洞察が得られます:

/test/path/B - 最優先で改善が必要

指標 値
トラフィック量 最大(ピーク時 6,000 リクエスト/分)
Total time 占有率 23.27%(最大)
平均レスポンスタイム 610ms

/test/path/Bへのトラフィックが最も多く、かつレスポンスタイムも遅いため、サーバー負荷への影響が最も大きいエンドポイントです。このエンドポイントを改善することで、全体のパフォーマンスに大きなインパクトを与えられます。
こちらに対して調査を行ったところ結論必要のない機能で呼び出し元の会社様に改善を求めたところピーク時のサーバーCPUで20%ぐらいの改善が見られました。

💡 まとめ

本記事では、Nginxアクセスログを効率的に解析し、Metabaseで可視化する方法を紹介しました。

GrafanaやNew Relicなどの監視ツールでも同様の分析は可能ですが、今回の手法は無料で手軽に始められる点が大きなメリットです。特別なインフラ構築や有料プランへの加入なしに、SQLの知識があればすぐにログ分析を始められます。

この手法により:

  • 膨大なログデータを日付単位で効率的に処理
  • SQLクエリで柔軟にデータを集計・分析
  • 視覚的なグラフでトラフィックパターンを即座に把握
    が可能になります。

さらに、New Relicを駆使することでそのエンドポイントのボトルネックになる処理を明確にして対応することができます。

継続的な監視体制の構築

今回の分析で得られた知見を活かし、今後は以下の監視体制を構築することを推奨します:

  • Grafanaによるアクセスログの傾向監視 - エンドポイントごとのリクエスト数やエラー率をダッシュボード化し、異常を早期に検知
  • New Relic APMの定期的なレビュー - 週次でトランザクション分布やレスポンスタイムの推移を確認し、パフォーマンス劣化の兆候を把握

これらの監視を継続的に行うことで、問題が顕在化する前に対処でき、サービスの安定運用につながります。パフォーマンス問題の原因特定に悩んでいるエンジニアの方は、ぜひこの手法を試してみてください。

Discussion