深色模式
journald 与 systemd 日志
现代 Linux 用 systemd-journald 收集内核与服务的结构化日志,统一存放在二进制日志环中。本文讲解用
journalctl高效检索与转发。
适用环境
bash
# 确认 journald 运行
systemctl status systemd-journald --no-pager
# 查看磁盘占用
journalctl --disk-usage1
2
3
4
2
3
4
操作步骤
1. 按服务查日志
bash
journalctl -u nginx.service -n 50 --no-pager
journalctl -u nginx.service -f # 实时跟踪1
2
2
2. 按时间、优先级过滤
bash
journalctl --since "2026-10-09 09:00:00" --until "2026-10-09 10:00:00"
journalctl -p err # 只看 error 及以上
journalctl _PID=1234 # 按进程1
2
3
2
3
3. 输出成 JSON 便于采集
bash
journalctl -u nginx.service -o json -n 201
4. 转发到 syslog/采集端
bash
# /etc/systemd/journald.conf
ForwardToSyslog=yes
# 重启生效
sudo systemctl restart systemd-journald1
2
3
4
2
3
4
验证
bash
journalctl -u nginx.service --since "1 hour ago" | tail -n 51
常见坑
WARNING
journald 默认有 SystemMaxUse 上限(通常 /var/log/journal 占磁盘 10%),日志会被循环覆盖。需要长期留存要调大或转发到远端。
DANGER
不要 journalctl --vacuum-time=... 在生产误清理关键日志;清理前先确认已转发备份。