0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonで構造化されたサンプルログを自動生成するスクリプトを作ってみた【テスト・検証・負荷試験に】

Posted at

🔰 背景と課題

ログ解析や監視ツールの検証を行う際、実際のログファイルを使うのは難しいことがあります。
なぜなら、実ログには機密情報や個人情報が含まれていることが多く、テストや外部共有には不向きだからです。

そこで今回は、Pythonでダミーログを構造的に自動生成するスクリプトを作ってみました。


🛠 このスクリプトでできること

  • ログ1行の本文サイズ(文字数)帯ごとに件数を指定して生成
  • タイムスタンプ/IP/ログレベル/アプリ名/メッセージを含んだ構造化ログ
  • CSVではなく、実際のログに近いスペース区切り形式
  • 各行で1秒ずつタイムスタンプを進めて出力
  • すべてを1ファイルにまとめて出力

🧱 ログの出力形式

以下のような形式で1行ごとのログを出力します:

2025-06-02 16:20:00 192.168.0.10 INFO auth aF84jK3qA...

項目 内容
timestamp ログ時刻(1秒ずつ増加)
ip ランダムなIPアドレス
priority INFO / WARN / ERRORなど
app_name アプリ名(auth, paymentなど)
message 指定サイズのランダム文字列

⚙️ 出力サイズの調整方法

以下のようにサイズ帯と件数を定義することで、出力されるメッセージの長さをコントロールできます:

size_distribution = [
    ((20, 30), 2),
    ((31, 50), 3),
    ((51, 80), 3),
    ((81, 128), 2),
]
この例では合計10行のログを出力しそれぞれの長さをランダムに分布させています

サンプルスクリプトloggen.py
import random
import string
from datetime import datetime, timedelta

# ======== 設定 ========

output_file = "sample_log.txt"  # 出力ファイル名
total_entries = 10              # 出力件数(自動算出)

size_distribution = [
    ((20, 30), 2),   # 短めログ 2件
    ((31, 50), 3),   # 中間ログ 3件
    ((51, 80), 3),   # 長めログ 3件
    ((81, 128), 2),  # 超長ログ 2件
]

ip_list = ["192.168.0.10", "10.0.0.1", "172.16.5.23"]
app_names = ["auth", "payment", "core"]
priorities = ["INFO", "WARN", "ERROR"]

# ======== エントリ生成 ========

log_entries = []
for (min_len, max_len), count in size_distribution:
    log_entries += [(min_len, max_len)] * count

start_time = datetime.now()

# ======== ログ出力 ========

with open(output_file, "w", encoding="utf-8") as f:
    for i, (min_len, max_len) in enumerate(log_entries):
        timestamp = (start_time + timedelta(seconds=i)).strftime("%Y-%m-%d %H:%M:%S")
        ip = random.choice(ip_list)
        priority = random.choice(priorities)
        app = random.choice(app_names)
        msg_len = random.randint(min_len, max_len)
        message = ''.join(random.choices(string.ascii_letters + string.digits, k=msg_len))

        line = f"{timestamp} {ip} {priority} {app} {message}"
        f.write(line + "\n")

print(f"ログ出力完了: {output_file}{len(log_entries)}件)")

ログの出力例

 $ python loggen.py
ログ出力完了: sample_log.txt10

$ cat sample_log.txt
2025-06-02 20:38:00 172.16.5.23 WARN payment 1nlWJdXK4yV4LTPiJAycaGjeEHG8X
2025-06-02 20:38:01 192.168.0.10 INFO payment R1GITPCDSnOFg1OFtvStq0TZF8rM
2025-06-02 20:38:02 172.16.5.23 WARN payment 4wVgF8IrNMtYQ6TF4NrIAjvuxrA912riN
...
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?