Pythonで複数のlog exportを検索する2 / 4
Parserと検索
次のscriptはfileを読み取ってWS-7だけを時刻順へし、無効な行をfile名/行番号で通知する。JSONLは一行に一objectを置き、値の改行はJSONとしてescapeする。
from pathlib import Path
from datetime import datetime, timezone
import json
import sys
events = []
fields = ("source", "time", "host", "observable", "action", "id")
for path in sorted(Path("exports").glob("*.jsonl")):
with path.open(encoding="utf-8") as stream:
for line_no, line in enumerate(stream, 1):
try:
record = json.loads(line)
if not isinstance(record, dict) or not all(isinstance(record.get(k), str) for k in fields):
raise ValueError("Invalid fields")
when = datetime.fromisoformat(record["time"].replace("Z", "+00:00"))
if when.tzinfo is None:
raise ValueError("Missing offset")
if record["host"] == "WS-7":
events.append((when.astimezone(timezone.utc), record))
except (ValueError, TypeError):
print(f"Invalid record: {path.name}:{line_no}", file=sys.stderr)
for when, record in sorted(events, key=lambda item: item[0]):
print(when.isoformat(), record["source"], record["action"], record["observable"])