实现说明
整个示例围绕函数 parse组织。
for line in lines 反复执行,循环体之外没有别的重复。
使用要点
- 跑完文件,输出里会留下标记——
unparseable:。
常见问题
运行「正则具名分组日志解析」会打印什么?
运行文件本身,unparseable: 这些前缀各对应一段演示逻辑。
签名一览:def parse(lines: list[str]) -> list[dict[str, str]]
核心语句
if match is None:
# 解析失败显式上报,而不是静默丢行
print(f'unparseable: {line[:40]}')
continue
代码示例
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']}")