linux journalctl 命令詳解

簡介

journalctl 是 Systemd 項目的一部分,Systemd 是一個系統和服務管理器,旨在提供一種更高級別的初始化系統。journalctl 是用來查詢和管理 systemd-journald 服務所維護的日誌文件的工具。journalctl 與傳統的日誌記錄方式相比,具有許多優勢,包括但不限於日誌數據的持久化存儲、壓縮存儲、以及對二進制數據的支持。

journalctl -h
journalctl [OPTIONS...] [MATCHES...]
Query the journal.
Source Options:
     --system                Show the system journal
     --user                  Show the user journal for the current user
  -M --machine=CONTAINER     Operate on local container
  -m --merge                 Show entries from all available journals
  -D --directory=PATH        Show journal files from directory
     --file=PATH             Show journal file
     --root=ROOT             Operate on files below a root directory
     --image=IMAGE           Operate on files in filesystem image
     --namespace=NAMESPACE   Show journal data from specified journal namespace
Filtering Options:
  -S --since=DATE            Show entries not older than the specified date
  -U --until=DATE            Show entries not newer than the specified date
  -c --cursor=CURSOR         Show entries starting at the specified cursor
     --after-cursor=CURSOR   Show entries after the specified cursor
     --cursor-file=FILE      Show entries after cursor in FILE and update FILE
  -b --boot[=ID]             Show current boot or the specified boot
  -u --unit=UNIT             Show logs from the specified unit
     --user-unit=UNIT        Show logs from the specified user unit
  -t --identifier=STRING     Show entries with the specified syslog identifier
  -p --priority=RANGE        Show entries within the specified priority range
     --facility=FACILITY...  Show entries with the specified facilities
  -g --grep=PATTERN          Show entries with MESSAGE matching PATTERN
     --case-sensitive[=BOOL] Force case sensitive or insensitive matching
  -k --dmesg                 Show kernel message log from the current boot
Output Control Options:
  -o --output=STRING         Change journal output mode (short, short-precise,
                               short-iso, short-iso-precise, short-full,
                               short-monotonic, short-unix, verbose, export,
                               json, json-pretty, json-sse, json-seq, cat,
                               with-unit)
     --output-fields=LIST    Select fields to print in verbose/export/json modes
  -n --lines[=INTEGER]       Number of journal entries to show
  -r --reverse               Show the newest entries first
     --show-cursor           Print the cursor after all the entries
     --utc                   Express time in Coordinated Universal Time (UTC)
  -x --catalog               Add message explanations where available
     --no-hostname           Suppress output of hostname field
     --no-full               Ellipsize fields
  -a --all                   Show all fields, including long and unprintable
  -f --follow                Follow the journal
     --no-tail               Show all lines, even in follow mode
  -q --quiet                 Do not show info messages and privilege warning
Pager Control Options:
     --no-pager              Do not pipe output into a pager
  -e --pager-end             Immediately jump to the end in the pager
Forward Secure Sealing (FSS) Options:
     --interval=TIME         Time interval for changing the FSS sealing key
     --verify-key=KEY        Specify FSS verification key
     --force                 Override of the FSS key pair with --setup-keys
Commands:
  -h --help                  Show this help text
     --version               Show package version
  -N --fields                List all field names currently used
  -F --field=FIELD           List all values that a specified field takes
     --list-boots            Show terse information about recorded boots
     --disk-usage            Show total disk usage of all journal files
     --vacuum-size=BYTES     Reduce disk usage below specified size
     --vacuum-files=INT      Leave only the specified number of journal files
     --vacuum-time=TIME      Remove journal files older than specified time
     --verify                Verify journal file consistency
     --sync                  Synchronize unwritten journal messages to disk
     --relinquish-var        Stop logging to disk, log to temporary file system
     --smart-relinquish-var  Similar, but NOP if log directory is on root mount
     --flush                 Flush all journal data from /run into /var
     --rotate                Request immediate rotation of the journal files
     --header                Show journal header information
     --list-catalog          Show all message IDs in the catalog
     --dump-catalog          Show entries in the message catalog
     --update-catalog        Update the message catalog database
     --setup-keys            Generate a new FSS key pair
See the journalctl(1) man page for details.

主要特點

  1. 統一的日誌存儲

    journalctl 使用統一的日誌存儲格式,允許將日誌信息和其他元數據(如時間戳、PID、UID、執行環境等)一起保存,使得日誌信息更加豐富。

  2. 持久存儲

    日誌不僅存儲在內存中,還會寫入到磁盤上的日誌文件中,確保即使系統崩潰也能恢復日誌數據。

  3. 壓縮存儲

    日誌文件可以被壓縮存儲,節省存儲空間。

  4. 支持二進制數據

    journalctl 可以記錄和檢索二進制數據,如截圖、核心轉儲等,這對於調試某些類型的問題非常有用。

  5. 高級搜索功能

    journalctl 提供了強大的搜索功能,可以通過各種條件篩選日誌,如時間範圍、用戶、進程名等。

  6. 支持日誌跟隨:

    可以實時顯示最新的日誌條目,類似於 tail -f 命令。

  7. 跨設備同步

    如果使用 NetworkManager,則可以通過網絡共享日誌,使得在一個機器上可以查看另一個機器的日誌。

基本用法

查看所有日誌

sudo journalctl

這會顯示所有已記錄的日誌條目,從最新的一條開始。由於輸出可能會非常多,因此默認情況下是倒序顯示,可以使用 Ctrl+C 終止輸出。

查看特定服務的日誌

如果你只想查看某個特定服務的日誌,可以使用 -u 參數:

sudo journalctl -u nginx.service

這會顯示屬於 nginx.service 的所有日誌條目。

指定時間範圍

如果你想查看某個時間段內的日誌,可以使用 --since 和 --until 參數:

sudo journalctl --since "2024-01-01" --until "2024-09-30"

實時跟蹤日誌

要實時查看最新的日誌條目,可以使用 -f 參數:

sudo journalctl -f

進階用法

journalctl 還支持複雜的查詢語法,允許用戶根據不同的條件過濾日誌,例如:

sudo journalctl _PID=1234 # 查看特定進程ID的日誌
sudo journalctl _COMM=nginx # 查看名爲nginx的日誌
sudo journalctl SYSLOG_FACILITY=daemon # 查看特定設施的日誌

配置管理

配置 journalctl 實際上是對 systemd-journald 服務的配置進行調整。配置文件位於 /etc/systemd/journald.conf,有時也會有運行時覆蓋文件 /run/systemd/journald.conf。下面是一些常見的配置項及其用途,以及如何進行配置。

配置文件的位置

主要的配置文件是 /etc/systemd/journald.conf。此文件包含了 systemd-journald 的全局設置。如果有需要,也可以在 /run/systemd/journald.conf 中添加運行時覆蓋配置。

常見配置項

存儲位置 (Storage=):

Storage=auto

日誌文件大小限制 (SystemMaxUse=):

SystemMaxUse=200M

日誌文件數量限制 (SystemMaxFiles=):

SystemMaxFiles=5

日誌壓縮 (Compress=):

Compress=yes

日誌過期時間 (SystemKeepFree=):

SystemKeepFree=1G

日誌旋轉 (ForwardToSyslog=):

ForwardToSyslog=yes

日誌轉發到 KERN (ForwardToKern=):

ForwardToKern=no

日誌記錄級別 (LogLevel=):

LogLevel=info

示例配置

假設你想更改日誌的存儲位置到 /var/lib/systemd/journal,並限制日誌文件的大小和數量,可以修改 /etc/systemd/journald.conf 文件如下:

[Journal]
Storage=persistent
SystemMaxUse=200M
SystemMaxFiles=5

應用配置更改

修改完配置文件後,需要重新加載 systemd 的配置才能使更改生效:

sudo systemctl daemon-reload

接着,重啓 systemd-journald 服務:

sudo systemctl restart systemd-journald

或者,你也可以直接重啓整個系統來確保所有更改都被應用。

運行時覆蓋

如果你希望在不編輯 /etc/systemd/journald.conf 文件的情況下臨時更改配置,可以創建或編輯 /run/systemd/journald.conf 文件。這個文件中的設置會覆蓋 /etc/systemd/journald.conf 中的設置。例如:

[Journal]
SystemMaxUse=100M
SystemMaxFiles=3

同樣地,修改完 /run/systemd/journald.conf 後,需要重啓 systemd-journald 服務:

sudo systemctl restart systemd-journald

通過以上步驟,可以根據自己的需求調整 journalctl 的行爲,以便更好地管理和分析系統日誌。

總結

journalctl 是一個強大的工具,爲 Linux 系統管理員提供了對系統日誌的高級管理和分析能力。通過了解其基本和高級功能,可以更有效地診斷系統問題,並保持系統的健康運行。

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/Rf4_iceAEENmdGim9xa2dg