journalctl 支持原生 JSON 输出,推荐使用 --output=json 生成 JSON Lines 格式;Python 应逐行解析,避免 json.load() 一次性加载;注意权限、禁用 json-pretty、时间戳需手动转换。

journalctl 支持原生输出 JSON 格式,无需额外转换,直接导出即可被 Python 的 json 模块安全加载。
使用 --output=json 导出标准 JSON 行格式
journalctl 默认的 json 输出是每行一个 JSON 对象(JSON Lines),这是最推荐的格式——兼容流式处理、避免大内存加载、Python 解析简单高效:
- 导出全部日志到文件:
journalctl --output=json > logs.jsonl - 按服务过滤并导出:
journalctl -u sshd --output=json > sshd_logs.jsonl - 限制最近 100 条:
journalctl -n 100 --output=json > recent.jsonl
用 Python 逐行解析 JSON Lines(推荐)
不要用 json.load() 一次性读整个文件(易爆内存、且 JSON Lines 不是合法单个 JSON);应逐行读取、逐行 json.loads():
import json
<p>with open("logs.jsonl", "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
try:
entry = json.loads(line)</p><h1>entry 是 dict,含 _time, _host, _pid, MESSAGE, SYSLOG_IDENTIFIER 等字段</h1><pre class="brush:php;toolbar:false;"> print(entry.get("MESSAGE"), entry.get("_host"))
except json.JSONDecodeError:
pass # 跳过损坏行(极少见)
Linux AI 服务器 — 将 Linux 服务器转换为本地 AI 推理集群。使用 systemd、NVIDIA CUDA 实现无头 Linux AI,零 GUI 开销。
立即学习“Python免费学习笔记(深入)”;
补充:导出带时间范围或结构化字段
可组合常用选项增强实用性:
- 指定时间范围:
journalctl --since="2024-05-01" --until="2024-05-02" --output=json > may1-2.jsonl - 包含所有字段(含二进制/空值):
journalctl --all --output=json(注意体积可能显著增大) - 只导出特定字段(需配合
--output=json-pretty或后处理):journalctl 本身不支持字段投影,如需精简,建议在 Python 中筛选 key,例如{k: v for k, v in entry.items() if k in ["@timestamp", "MESSAGE", "PRIORITY"]}
小提示:避免常见坑
注意权限:普通用户可能无法读取全部日志,加 sudo 或将用户加入 systemd-journal 组。
别用 --output=json-pretty:它生成缩进格式的单个 JSON 数组,既难流式解析,又容易因日志量大导致 OOM;仅适合调试查看,不适合分析。
时间字段是字符串:所有时间字段(如 __REALTIME_TIMESTAMP)都是微秒级 Unix 时间戳字符串,Python 中可用 int(ts) // 10**6 转为秒级时间戳,再用 datetime.fromtimestamp() 处理。

















