Regex Named Group Log Parsing

Turn unstructured log lines into typed dicts with named capture groups and one compiled pattern, rejecting malformed lines explicitly.

PythonData Integrity

Code

pythonsnippet
33 lines
import re

# 具名分组让提取逻辑自文档化;pattern 只编译一次
LINE = re.compile(
    r'^(?P<ts>\\d{4}-\\d{2}-\\d{2}T[\\d:]+) '
    r'(?P<level>INFO|WARN|ERROR) '
    r'(?P<logger>[\\w.]+) - (?P<message>.*)$'
)

LOG_LINES = [
    '2026-11-09T10:15:04 INFO app.api - request served in 42ms',
    '2026-11-09T10:15:06 WARN app.db - pool at 80% capacity',
    'this line is garbage',
    '2026-11-09T10:16:00 ERROR app.worker - job 42 failed: timeout',
]


def parse(lines: list[str]) -> list[dict[str, str]]:
    parsed = []
    for line in lines:
        match = LINE.match(line)
        if match is None:
            # 解析失败显式上报,而不是静默丢行
            print(f'unparseable: {line[:40]}')
            continue
        parsed.append(match.groupdict())
    return parsed


if __name__ == '__main__':
    rows = parse(LOG_LINES)
    for row in rows:
        print(f"{row['level']:<5} {row['logger']:<8} {row['message']}")

Output

Captured from a sandboxed run of this snippet in the build pipeline.

unparseable: 2026-11-09T10:15:04 INFO app.api - reque
unparseable: 2026-11-09T10:15:06 WARN app.db - pool a
unparseable: this line is garbage
unparseable: 2026-11-09T10:16:00 ERROR app.worker - j

What the code does

Regex Named Group Log Parsing keeps everything in the function parse.

Iteration happens inside for line in lines — everything outside it runs once.

Applying it

The main signature reads def parse(lines: list[str]) -> list[dict[str, str]]

Output lines are prefixed (unparseable:), making each step’s effect easy to spot.

Statements that matter

if match is None:
    # 解析失败显式上报,而不是静默丢行
    print(f'unparseable: {line[:40]}')
    continue

Interactive Tools for This Topic

FAQ

What does Regex Named Group Log Parsing print when run?
Invoke the file as-is — the `unparseable:` prefixes identify which step printed each line.