Files

79 lines
3.6 KiB
Python
Executable File

#!/usr/bin/env python3
# fakelog - generate fake log lines for testing log tools
# Usage: fakelog [-n LINES] [--format apache|syslog|json] [--seed N]
import argparse, datetime, json, random, sys
HOSTS = ["web01", "web02", "db01", "cache01", "api02"]
IPS = ["192.168.1.10", "10.0.0.42", "203.0.113.7", "198.51.100.23", "172.16.0.99"]
METHODS = ["GET", "POST", "PUT", "DELETE", "HEAD"]
PATHS = ["/", "/index.html", "/api/users", "/api/orders", "/login", "/static/app.js",
"/images/logo.png", "/api/search?q=test", "/health", "/dashboard"]
STATUSES = [200, 200, 200, 200, 201, 301, 304, 400, 404, 404, 500]
UAS = ["Mozilla/5.0 (X11; Linux x86_64)", "curl/8.5.0", "Mozilla/5.0 (Windows NT 10.0)",
"Go-http-client/2.0", "python-requests/2.31.0"]
SYS_MSGS = ["Accepted password for root from 192.168.1.10 port 51234 ssh2",
"systemd[1]: Started Daily apt download activities.",
"kernel: [ 123.456] usb 1-1: new high-speed USB device",
"cron[1234]: (root) CMD (/usr/local/bin/backup.sh)",
"nginx: 2026/12/03 10:00:00 [error] connect() failed (111: Connection refused)",
"postgres: checkpoint complete: wrote 42 buffers",
"docker: container abc123 started", "sshd[5678]: Disconnected from user test"]
LEVELS = ["INFO", "WARN", "ERROR", "DEBUG"]
def apache_line(rng, base):
dt = base + datetime.timedelta(seconds=rng.randint(0, 3600))
return (f'{rng.choice(IPS)} - - [{dt.strftime("%d/%b/%Y:%H:%M:%S +0000")}] '
f'"{rng.choice(METHODS)} {rng.choice(PATHS)} HTTP/1.1" '
f'{rng.choice(STATUSES)} {rng.randint(120, 65536)} '
f'"-" "{rng.choice(UAS)}"')
def syslog_line(rng, base):
dt = base + datetime.timedelta(seconds=rng.randint(0, 3600))
return (f'{dt.strftime("%b %d %H:%M:%S")} {rng.choice(HOSTS)} '
f'{rng.choice(SYS_MSGS)}')
def json_line(rng, base):
dt = base + datetime.timedelta(seconds=rng.randint(0, 3600))
return json.dumps({
"timestamp": dt.isoformat() + "Z",
"level": rng.choice(LEVELS),
"service": rng.choice(["web", "api", "db", "worker"]),
"host": rng.choice(HOSTS),
"message": rng.choice(SYS_MSGS),
"status": rng.choice(STATUSES),
})
def generate(n, fmt, seed=None):
rng = random.Random(seed)
base = datetime.datetime(2026, 12, 3, 10, 0, 0)
fn = {"apache": apache_line, "syslog": syslog_line, "json": json_line}[fmt]
return [fn(rng, base) for _ in range(n)]
def selftest():
for fmt in ("apache", "syslog", "json"):
lines = generate(5, fmt, seed=7)
assert len(lines) == 5 and all(lines), fmt
assert generate(5, fmt, seed=7) == lines
assert "GET" in " ".join(generate(20, "apache", seed=1)) or True
j = json.loads(generate(1, "json", seed=1)[0])
assert "timestamp" in j and "level" in j
for line in generate(3, "apache", seed=3):
print(line)
print("fakelog selftest OK")
def main():
p = argparse.ArgumentParser(description="Generate fake log lines for testing log tools.")
p.add_argument("-n", "--lines", type=int, default=10, help="number of lines (default 10)")
p.add_argument("--format", choices=["apache", "syslog", "json"], default="apache",
help="log format (default apache)")
p.add_argument("--seed", type=int, default=None, help="seed for deterministic output")
p.add_argument("--selftest", action="store_true", help="run a built-in self-test and exit")
a = p.parse_args()
if a.selftest:
selftest(); return 0
print("\n".join(generate(max(1, a.lines), a.format, a.seed)))
return 0
if __name__ == "__main__":
sys.exit(main())