Modern QA2026Regular Expressions for Log Parsing — tiles
Log inJoin
53 / 80 · 12 Programming for QA · Regex and Parsing← prev⊞ allnext →☰ Read as one page

7.2Regular Expressions for Log Parsing

import re

log_line = '2024-03-15 14:23:01 ERROR [PaymentService] Transaction TX-98712 failed: insufficient_funds'

# Extract transaction ID
match = re.search(r'TX-\d+', log_line)
tx_id = match.group()  # "TX-98712"

# Extract log level
level = re.search(r'\b(DEBUG|INFO|WARN|ERROR|FATAL)\b', log_line).group()  # "ERROR"

# Extract timestamp
timestamp = re.search(r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}', log_line).group()

# Parse multiple log lines
with open("app.log") as f:
    errors = [line for line in f if re.search(r'\bERROR\b', line)]
    print(f"Found {len(errors)} error lines")