journalctl 日誌查詢常用招式
systemd 的日誌不用再翻一堆檔案。用 journalctl 依服務、時間、優先級快速過濾。
在 systemd 系統上,大部分服務的日誌都進了 journal。學會 journalctl 的幾個過濾方式,排錯會快很多。
依服務
journalctl -u nginx.service # 某個服務的全部日誌
journalctl -u nginx -n 50 # 最近 50 行
journalctl -u nginx -f # 即時追蹤(像 tail -f)
依時間
journalctl --since "2026-01-01" --until "2026-01-02"
journalctl --since "1 hour ago"
journalctl -u app --since today
依優先級
只看錯誤等級以上的:
journalctl -p err -b # 本次開機以來的 err 以上
journalctl -p warning..err # 指定範圍
優先級:emerg alert crit err warning notice info debug。
本次開機 / 上次開機
journalctl -b # 本次開機
journalctl -b -1 # 上一次開機(查當機原因很有用)
journalctl --list-boots
其他實用選項
| 選項 | 作用 |
|---|---|
-k | 只看核心訊息(dmesg) |
-o json-pretty | JSON 格式輸出 |
-g 關鍵字 | grep 過濾(需較新版本) |
--no-pager | 不進 pager,適合接管線 |
控制日誌大小
journalctl --disk-usage # 目前佔用
journalctl --vacuum-size=500M # 縮到 500M 以內
journalctl --vacuum-time=30d # 只留 30 天
長期上限建議在 /etc/systemd/journald.conf 設 SystemMaxUse=500M,一勞永逸。