Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình

Thành thạo systemd Logs: Hướng dẫn hoàn chỉnh dùng journalctl trên Linux

Giới thiệu về systemd Journal và journalctl Logging

Một số lợi thế thuyết phục nhất của systemd là những liên quan đến process và system logging. Khi dùng các công cụ khác, log thường phân rải khắp hệ thống, được xử lý bởi các daemon và process khác nhau, và khá khó diễn giải khi chúng trải qua nhiều ứng dụng. systemd cố gắng giải quyết vấn đề này bằng cách cung cấp giải pháp quản lý tập trung cho việc logging tất cả kernel và userland processes. Hệ thống thu thập và quản lý log này được gọi là journal.

Journal được triển khai với daemon journald, xử lý tất cả message từ kernel, initrd, services, v.v. Trong hướng dẫn này, chúng ta sẽ thảo luận cách dùng tiện ích journalctl, có thể dùng để truy cập và thao tác dữ liệu trong journal.

Trong bài viết này, bạn sẽ học cách dùng công cụ command-line journalctl để truy cập và lọc log data từ systemd journal. Chúng ta sẽ bao gồm cách xem log từ boot sessions hoặc time ranges cụ thể, lọc theo systemd units, users, hoặc priority levels, và output log ở format như JSON để tích hợp với công cụ khác. Bạn cũng sẽ học cách monitor real-time events, quản lý disk usage, cấu hình persistent logging, và giải quyết common issues như missing logs hoặc permission errors. Dù bạn đang debug failing service hay thiết lập centralized log collection, journalctl cung cấp flexibility và precision để streamline workflow.

Các điểm chính

  • Systemd journal cung cấp unified logging system capture message từ kernel, services, và user applications trong một log tập trung, indexed.
  • Lệnh journalctl cho phép lọc log theo boot sessions, time ranges, systemd units, process IDs, user IDs, group IDs, và hơn thế nữa, giúp dễ dàng pinpoint relevant events.
  • Bạn có thể retrieve log từ time windows cụ thể dùng options như --since, --until, hoặc relative expressions như "1 hour ago" hoặc "yesterday".
  • Log có thể hiển thị ở nhiều format như plain text, JSON, và verbose mode, dễ dàng tích hợp với external tools hoặc parse để phân tích.
  • Dùng journalctl -f, bạn có thể follow log messages live khi chúng được viết, tương tự tail -f, hữu ích cho monitoring system activity hoặc service behavior real-time.
  • Mặc định, log có thể lưu trong memory và mất khi reboot. Bạn có thể enable persistent logging bằng cách tạo /var/log/journal và cấu hình journald.conf tương ứng.
  • Storage footprint của journal có thể quản lý với commands như --disk-usage, --vacuum-size, và --vacuum-time, cũng như configuration options để control maximum size và retention.
  • journalctl đơn giản hóa service debugging bằng cách aggregate log across boots và units, làm dễ dàng identify failures, track SSH access, và investigate issues với detailed context.

Cách systemd Journal hoạt động và tại sao nó quan trọng

Một trong những động lực behind systemd journal là tập trung quản lý log bất kể message xuất phát từ đâu. Vì nhiều boot process và service management được handle bởi process systemd, việc standardize cách log được collect và access là hợp lý. Daemon journald thu thập data từ tất cả available sources và lưu trữ ở binary format để dễ dàng manipulate động.

Điều này cho chúng ta nhiều lợi thế đáng kể. Bằng cách interact với data dùng single utility, administrator có thể dynamically display log data theo nhu cầu. Điều này có thể đơn giản như xem boot data từ ba boot trước, hoặc combine log entries sequentially từ hai related services để debug communication issue.

Lưu trữ log data ở binary format cũng nghĩa là data có thể hiển thị ở arbitrary output formats tùy bạn cần lúc đó. Ví dụ, cho daily log management bạn có thể quen xem log ở standard syslog format, nhưng nếu quyết định graph service interruptions sau, bạn có thể output mỗi entry như JSON object để consumable cho graphing service. Vì data không viết ra disk ở plain text, không cần conversion khi cần format on-demand khác.

Systemd journal có thể dùng với existing syslog implementation, hoặc replace syslog functionality, tùy nhu cầu. Trong khi systemd journal cover hầu hết logging needs của administrator, nó cũng complement existing logging mechanisms. Ví dụ, bạn có centralized syslog server compile data từ nhiều server, nhưng cũng muốn interleave log từ nhiều services trên single system với systemd journal. Bạn có thể làm cả hai bằng cách combine technologies.

Cách set Correct System Time với timedatectl

Một lợi ích của binary journal cho logging là khả năng view log records ở UTC hoặc local time tùy ý. Mặc định, systemd hiển thị kết quả ở local time.

Vì vậy, trước khi bắt đầu với journal, chúng ta sẽ đảm bảo timezone được set đúng. Suite systemd thực sự có tool gọi timedatectl giúp với việc này.

Đầu tiên, xem timezones available với option list-timezones:

timedatectl list-timezones

Điều này liệt kê timezones available trên hệ thống. Khi tìm thấy timezone khớp với location server, bạn set nó dùng option set-timezone:

sudo timedatectl set-timezone zone

Để đảm bảo machine dùng đúng time, dùng lệnh timedatectl đơn lẻ, hoặc với option status. Hiển thị sẽ giống nhau:

timedatectl status
 Local time: Fri 2021-07-09 14:44:30 EDT Universal time: Fri 2021-07-09 18:44:30 UTC RTC time: Fri 2021-07-09 18:44:31 Time zone: America/New_York (EDT, -0400) System clock synchronized: yes NTP service: active RTC in local TZ: no 

Dòng đầu nên hiển thị correct time.

Cách View Logs với journalctl

Để xem log mà daemon journald thu thập, dùng lệnh journalctl.

Khi dùng đơn lẻ, mọi journal entry trong hệ thống sẽ hiển thị trong pager (thường là less) để bạn browse. Entry cũ nhất ở trên:

journalctl
-- Logs begin at Tue 2015-02-03 21:48:52 UTC, end at Tue 2015-02-03 22:29:38 UTC. -- Feb 03 21:48:52 localhost.localdomain systemd-journal[243]: Runtime journal is using 6.2M (max allowed 49. Feb 03 21:48:52 localhost.localdomain systemd-journal[243]: Runtime journal is using 6.2M (max allowed 49. Feb 03 21:48:52 localhost.localdomain systemd-journald[139]: Received SIGTERM from PID 1 (systemd). Feb 03 21:48:52 localhost.localdomain kernel: audit: type=1404 audit(1423000132.274:2): enforcing=1 old_en Feb 03 21:48:52 localhost.localdomain kernel: SELinux: 2048 avtab hash slots, 104131 rules. Feb 03 21:48:52 localhost.localdomain kernel: SELinux: 2048 avtab hash slots, 104131 rules. Feb 03 21:48:52 localhost.localdomain kernel: input: ImExPS/2 Generic Explorer Mouse as /devices/platform/ Feb 03 21:48:52 localhost.localdomain kernel: SELinux: 8 users, 102 roles, 4976 types, 294 bools, 1 sens, Feb 03 21:48:52 localhost.localdomain kernel: SELinux: 83 classes, 104131 rules . . . 

Bạn có thể có hàng trang data để scroll, có thể hàng chục hoặc hàng trăm nghìn dòng nếu systemd đã trên hệ thống lâu. Điều này demo lượng data lớn available trong journal database.

Format sẽ quen thuộc với những ai dùng standard syslog logging. Tuy nhiên, này thực sự collect data từ nhiều sources hơn traditional syslog implementations capable. Nó bao gồm log từ early boot process, kernel, initrd, và application standard error và out. Tất cả available trong journal.

Bạn có thể nhận thấy tất cả timestamps hiển thị là local time. Điều này available cho mọi log entry bây giờ vì chúng ta set local time đúng trên hệ thống. Tất cả log hiển thị dùng thông tin mới này.

Nếu muốn hiển thị timestamps ở UTC, dùng flag --utc:

journalctl --utc

Cách Filter systemd Logs by Time với journalctl

Mặc dù access large collection data chắc chắn hữu ích, lượng lớn thông tin đó có thể khó hoặc không thể inspect và process manually. Vì vậy, một trong những feature quan trọng nhất của journalctl là filtering options.

Show Logs từ Current Boot Session với journalctl

Basic nhất trong những cái bạn có thể dùng hàng ngày là flag -b. Nó show tất cả journal entries collected kể từ recent reboot nhất.

journalctl -b

Điều này giúp identify và manage information pertinent đến current environment.

Trong trường hợp bạn không dùng feature này và hiển thị nhiều ngày boot, bạn sẽ thấy journalctl chèn một line trông như sau mỗi khi system down:

. . . -- Reboot -- . . . 

Điều này có thể giúp logically separate information thành boot sessions.

Cách Access Logs từ Previous Boots dùng journalctl

Mặc dù bạn thường muốn display info từ current boot, chắc chắn có lúc past boots hữu ích. Journal có thể save info từ nhiều previous boots, nên journalctl có thể display info dễ dàng.

Một số distributions enable saving previous boot info mặc định, những cái khác disable feature. Để enable persistent boot info, bạn có thể tạo directory lưu journal bằng:

sudo mkdir -p /var/log/journal

Hoặc edit journal configuration file:

sudo nano /etc/systemd/journald.conf

Dưới section [Journal], set option Storage= thành "persistent" để enable persistent logging:

/etc/systemd/journald.conf

. . . [Journal] Storage=persistent 

Khi saving previous boots enabled trên server, journalctl cung cấp commands giúp work với boots như unit of division. Để xem boots mà journald biết, dùng option --list-boots với journalctl:

journalctl --list-boots
-2 caf0524a1d394ce0bdbcff75b94444fe Tue 2015-02-03 21:48:52 UTC—Tue 2015-02-03 22:17:00 UTC -1 13883d180dc0420db0abcb5fa26d6198 Tue 2015-02-03 22:17:03 UTC—Tue 2015-02-03 22:19:08 UTC 0 bed718b17a73415fade0e4e7f4bea609 Tue 2015-02-03 22:19:12 UTC—Tue 2015-02-03 23:01:01 UTC 

Điều này display một line cho mỗi boot. Cột đầu là offset cho boot dùng để easily reference boot với journalctl. Nếu cần absolute reference, boot ID ở cột thứ hai. Bạn có thể biết time boot session refer đến với hai time specifications ở cuối.

Để display info từ boots này, bạn dùng info từ cột đầu hoặc hai.

Ví dụ, để xem journal từ previous boot, dùng relative pointer -1 với flag -b:

journalctl -b -1

Bạn cũng dùng boot ID để gọi data từ boot:

journalctl -b caf0524a1d394ce0bdbcff75b94444fe

Filter journalctl Logs by Custom Date và Time Ranges

Mặc dù xem log entries by boot cực hữu ích, thường bạn muốn request time windows không align tốt với system boots. Điều này đặc biệt true khi deal với long-running servers với significant uptime.

Bạn có thể filter bằng arbitrary time limits dùng options --since và --until, restrict entries displayed đến those after hoặc before given time, tương ứng.

Time values có thể ở nhiều format. Cho absolute time values, dùng format sau:

YYYY-MM-DD HH:MM:SS

Ví dụ, xem tất cả entries kể từ Jan 10, 2015 lúc 5:15 PM bằng:

journalctl --since "2015-01-10 17:15:00"

Nếu components của format trên bỏ qua, một số defaults sẽ applied. Ví dụ, nếu date omitted, current date assumed. Nếu time component missing, "00:00:00" (midnight) substituted. Seconds field cũng có thể bỏ để default "00":

journalctl --since "2015-01-10" --until "2015-01-11 03:00"

Journal cũng hiểu một số relative values và named shortcuts. Ví dụ, bạn dùng từ "yesterday", "today", "tomorrow", hoặc "now". Relative times bằng cách prepend "-" hoặc "+" vào numbered value hoặc dùng từ như "ago" trong câu.

Để lấy data từ hôm qua, gõ:

journalctl --since yesterday

Nếu nhận báo cáo service interruption bắt đầu 9:00 AM và kéo dài đến một giờ trước, gõ:

journalctl --since 09:00 --until "1 hour ago"

Như bạn thấy, relative straightforward để define flexible time windows filter entries bạn muốn xem.

Cách Filter systemd Journal Logs by Service, PID, hoặc User

Trên, chúng ta học cách filter journal data dùng time constraints. Phần này discuss cách filter based trên service hoặc component bạn quan tâm. Systemd journal cung cấp nhiều cách làm điều này.

View Logs by Systemd Service Unit

Có lẽ cách filter hữu ích nhất là by unit bạn quan tâm. Chúng ta dùng option -u filter cách này.

Ví dụ, để xem tất cả log từ Nginx unit trên hệ thống, gõ:

journalctl -u nginx.service

Thông thường, bạn muốn filter by time cũng để display lines bạn quan tâm. Ví dụ, check service chạy hôm nay thế nào, gõ:

journalctl -u nginx.service --since today

Loại focus này cực hữu ích khi tận dụng ability của journal interleave records từ various units. Ví dụ, nếu Nginx process kết nối PHP-FPM unit xử lý dynamic content, bạn merge entries từ cả hai theo chronological order bằng cách specify cả hai units:

journalctl -u nginx.service -u php-fpm.service --since today

Điều này làm dễ dàng spot interactions giữa các programs và debug systems thay vì individual processes.

Filter systemd Logs by PID, UID, hoặc GID

Một số services spawn nhiều child processes làm việc. Nếu bạn scouted exact PID của process quan tâm, bạn filter by đó cũng được.

Làm điều này bằng cách specify field _PID. Ví dụ nếu PID quan tâm là 8088, gõ:

journalctl _PID=8088

Lúc khác, bạn muốn show tất cả entries logged từ specific user hoặc group. Làm được với filter _UID hoặc _GID. Ví dụ, nếu web server chạy dưới user www-data, tìm user ID bằng:

id -u www-data
33 

Sau đó, dùng ID returned filter journal results:

journalctl _UID=33 --since today

Systemd journal có nhiều fields dùng cho filtering. Một số passed từ process being logged và một số applied bởi journald dùng info gather từ system tại thời điểm log.

Leading underscore chỉ ra field _PID là loại sau. Journal tự động record và index PID của process logging để filter sau. Bạn tìm hiểu tất cả available journal fields bằng:

man systemd.journal-fields

Chúng ta sẽ discuss một số trong guide. Hiện tại, đi qua một option hữu ích nữa liên quan filter by fields. Option -F dùng show all available values cho given journal field.

Ví dụ, xem group IDs systemd journal có entries, gõ:

journalctl -F _GID
32 99 102 133 81 84 100 0 124 87 

Điều này show tất cả values journal stored cho group ID field. Giúp construct filters.

View Logs by Executable Path

Chúng ta cũng filter bằng cách cung cấp path location.

Nếu path dẫn đến executable, journalctl display tất cả entries involve executable. Ví dụ, tìm entries involve bash executable, gõ:

journalctl /usr/bin/bash

Thường, nếu unit available cho executable, method đó cleaner và better info (entries từ associated child processes, etc). Đôi khi, tuy nhiên, điều này không possible.

Cách View Kernel Logs dùng journalctl -k

Kernel messages, thường thấy trong output dmesg, cũng retrieve từ journal.

Để display chỉ messages này, thêm flag -k hoặc --dmesg:

journalctl -k

Mặc định, này display kernel messages từ current boot. Bạn specify alternative boot dùng normal boot selection flags thảo luận trước. Ví dụ, lấy messages từ năm boot trước, gõ:

journalctl -k -b -5

Filter Logs by Severity Level với journalctl -p

Một filter system administrators thường quan tâm là message priority. Mặc dù log info ở verbose level hữu ích, khi digest available information, low priority logs có thể distracting và confusing.

Bạn dùng journalctl display chỉ messages ở specified priority hoặc above dùng option -p. Điều này filter out lower priority messages.

Ví dụ, show chỉ entries logged ở error level hoặc above, gõ:

journalctl -p err -b

Điều này show all messages marked error, critical, alert, hoặc emergency. Journal implement standard syslog message levels. Bạn dùng priority name hoặc numeric value tương ứng. Theo thứ tự highest đến lowest priority:

  • 0: emerg
  • 1: alert
  • 2: crit
  • 3: err
  • 4: warning
  • 5: notice
  • 6: info
  • 7: debug

Các số hoặc tên trên dùng interchangeably với option -p. Chọn priority display messages marked ở level specified và those above it.

Customize journalctl Log Output Display

Trên, chúng ta demo entry selection qua filtering. Có cách khác modify output. Chúng ta adjust journalctl display fit various needs.

Cách Control Output Length và Formatting trong journalctl

Chúng ta adjust cách journalctl display data bằng cách bảo nó shrink hoặc expand output.

Mặc định, journalctl show entire entry trong pager, cho entries trail off bên phải màn hình. Info này access bằng right arrow key.

Nếu muốn output truncated, insert ellipsis nơi info removed, dùng option --no-full:

journalctl --no-full
. . . Feb 04 20:54:13 journalme sshd[937]: Failed password for root from 83.234.207.60...h2 Feb 04 20:54:13 journalme sshd[937]: Connection closed by 83.234.207.60 [preauth] Feb 04 20:54:13 journalme sshd[937]: PAM 2 more authentication failures; logname...ot 

Bạn cũng đi ngược lại với này và bảo journalctl display all information, bất kể có unprintable characters. Làm được với flag -a:

journalctl -a

Cách Disable Pager trong journalctl Output

Mặc định, journalctl display output trong pager cho easier consumption. Nếu bạn plan process data với text manipulation tools, bạn probably want output to standard output.

Làm được với option --no-pager:

journalctl --no-pager

Điều này có thể piped ngay vào processing utility hoặc redirected vào file on disk, tùy needs.

Different Output Formats trong journalctl

Nếu bạn processing journal entries, như trên, bạn most likely easier time parse data nếu nó ở consumable format hơn. May mắn, journal có thể display ở variety of formats as needed. Làm được dùng option -o với format specifier.

Ví dụ, output journal entries ở JSON bằng:

journalctl -b -u nginx -o json
{ "__CURSOR" : "s=13a21661cf4948289c63075db6c25c00;i=116f1;b=81b58db8fd9046ab9f847ddb82a2fa2d;m=19f0daa;t=50e33c33587ae;x=e307daadb4858635", "__REALTIME_TIMESTAMP" : "1422990364739502", "__MONOTONIC_TIMESTAMP" : "27200938", "_BOOT_ID" : "81b58db8fd9046ab9f847ddb82a2fa2d", "PRIORITY" : "6", "_UID" : "0", "_GID" : "0", "_CAP_EFFECTIVE" : "3fffffffff", "_MACHINE_ID" : "752737531a9d1a9c1e3cb52a4ab967ee", "_HOSTNAME" : "desktop", "SYSLOG_FACILITY" : "3", "CODE_FILE" : "src/core/unit.c", "CODE_LINE" : "1402", "CODE_FUNCTION" : "unit_status_log_starting_stopping_reloading", "SYSLOG_IDENTIFIER" : "systemd", "MESSAGE_ID" : "7d4958e842da4a758f6c1cdc7b36dcc5", "_TRANSPORT" : "journal", "_PID" : "1", "_COMM" : "systemd", "_EXE" : "/usr/lib/systemd/systemd", "_CMDLINE" : "/usr/lib/systemd/systemd", "_SYSTEMD_CGROUP" : "/", "UNIT" : "nginx.service", "MESSAGE" : "Starting A high performance web server and a reverse proxy server...", "_SOURCE_REALTIME_TIMESTAMP" : "1422990364737973" } . . . 

Hữu ích cho parsing với utilities. Bạn dùng format json-pretty để better handle data structure trước khi pass off to JSON consumer:

journalctl -b -u nginx -o json-pretty
{ "__CURSOR" : "s=13a21661cf4948289c63075db6c25c00;i=116f1;b=81b58db8fd9046ab9f847ddb82a2fa2d;m=19f0daa;t=50e33c33587ae;x=e307daadb4858635", "__REALTIME_TIMESTAMP" : "1422990364739502", "__MONOTONIC_TIMESTAMP" : "27200938", "_BOOT_ID" : "81b58db8fd9046ab9f847ddb82a2fa2d", "PRIORITY" : "6", "_UID" : "0", "_GID" : "0", "_CAP_EFFECTIVE" : "3fffffffff", "_MACHINE_ID" : "752737531a9d1a9c1e3cb52a4ab967ee", "_HOSTNAME" : "desktop", "SYSLOG_FACILITY" : "3", "CODE_FILE" : "src/core/unit.c", "CODE_LINE" : "1402", "CODE_FUNCTION" : "unit_status_log_starting_stopping_reloading", "SYSLOG_IDENTIFIER" : "systemd", "MESSAGE_ID" : "7d4958e842da4a758f6c1cdc7b36dcc5", "_TRANSPORT" : "journal", "_PID" : "1", "_COMM" : "systemd", "_EXE" : "/usr/lib/systemd/systemd", "_CMDLINE" : "/usr/lib/systemd/systemd", "_SYSTEMD_CGROUP" : "/", "UNIT" : "nginx.service", "MESSAGE" : "Starting A high performance web server and a reverse proxy server...", "_SOURCE_REALTIME_TIMESTAMP" : "1422990364737973" } . . . 

Các format sau dùng cho display:

  • cat: Chỉ display message field itself.
  • export: Binary format suitable cho transferring hoặc backing up.
  • json: Standard JSON với one entry per line.
  • json-pretty: JSON formatted cho better human-readability
  • json-sse: JSON formatted output wrapped để make add server-sent event compatible
  • short: Default syslog style output
  • short-iso: Default format augmented show ISO 8601 wallclock timestamps.
  • short-monotonic: Default format với monotonic timestamps.
  • short-precise: Default format với microsecond precision
  • verbose: Show every journal field available cho entry, bao gồm those usually hidden internally.

Các option này cho phép display journal entries ở format nào best suits current needs.

Monitor Live systemd Logs với journalctl

Lệnh journalctl imitate cách nhiều administrator dùng tail monitoring active hoặc recent activity. Functionality này built into journalctl, cho phép access features này không pipe to another tool.

Show Recent Log Entries với journalctl -n

Để display set amount records, dùng option -n, works exactly như tail -n.

Mặc định, display 10 recent entries:

journalctl -n

Bạn specify number entries bạn muốn xem với number sau -n:

journalctl -n 20

Follow Real-Time Logs với journalctl -f

Để actively follow logs khi chúng được written, dùng flag -f. Lại, works như bạn expect nếu có experience dùng tail -f:

journalctl -f

Để exit command, type CTRL+C.

Cách Manage và Clean Up systemd Journal Logs

Bạn có thể wonder về cost of storing all data chúng ta thấy. Hơn nữa, bạn có thể interested clean up older logs và free up space.

Check Disk Usage của systemd Logs với journalctl --disk-usage

Bạn find out amount of space journal currently occupying on disk dùng flag --disk-usage:

journalctl --disk-usage
Archived and active journals take up 8.0M in the file system. 

Delete Old Logs với journalctl --vacuum-size và --vacuum-time

Nếu muốn shrink journal, làm được theo hai cách khác nhau (available với systemd version 218 và sau).

Nếu dùng option --vacuum-size, shrink journal bằng cách indicate size. Điều này remove old entries cho đến total journal space taken up on disk ở requested size:

sudo journalctl --vacuum-size=1G

Cách khác shrink journal là cung cấp cutoff time với option --vacuum-time. Entries beyond time đó deleted. Cho phép keep entries created after specific time.

Ví dụ, keep entries từ năm qua, gõ:

sudo journalctl --vacuum-time=1years

Configure Disk Space Limits cho Journald Logs

Bạn configure server place limits trên space journal có thể take up. Làm được bằng edit file /etc/systemd/journald.conf.

Các items sau dùng limit journal growth:

  • SystemMaxUse=: Specifies maximum disk space journal dùng trong persistent storage.
  • SystemKeepFree=: Specifies amount of space journal nên leave free khi add journal entries to persistent storage.
  • SystemMaxFileSize=: Controls large individual journal files grow trong persistent storage trước khi rotated.
  • RuntimeMaxUse=: Specifies maximum disk space dùng trong volatile storage (trong /run filesystem).
  • RuntimeKeepFree=: Specifies amount of space set aside cho other uses khi write data to volatile storage (trong /run filesystem).
  • RuntimeMaxFileSize=: Specifies amount of space individual journal file take up trong volatile storage (trong /run filesystem) trước khi rotated.

Bằng cách set các values, bạn control cách journald consumes và preserves space trên server. Nhớ rằng SystemMaxFileSize và RuntimeMaxFileSize target archived files để reach stated limits. Quan trọng remember khi interpret file counts sau vacuuming operation.

Troubleshooting Common journalctl và systemd Journal Issues

1. Tại sao journalctl Không Show Logs?

Trong một số cases, bạn chạy journalctl expect log output, chỉ gặp blank screen hoặc no meaningful results. Situation này confusing, đặc biệt nếu troubleshooting issue hoặc tìm recent system activity. May mắn, có several common explanations demystify tại sao journalctl không show logs.

The Journal Database Is Empty hoặc Missing

Một trong những lý do straightforward để thấy no output là journal empty. Điều này xảy ra trên newly installed systems, minimal container environments, hoặc servers nơi system logging chưa generate entries. Cũng possible hệ thống configured chỉ store logs trong memory (volatile storage), nghĩa là all logs erased on reboot. Để check persistent logging enabled, look for presence của journal directory:

ls /var/log/journal 

Nếu directory này không exist, hoặc empty, nghĩa là logs không saved between boots. Bạn resolve bằng cách tạo directory và restart journald service:

sudo mkdir -p /var/log/journal sudo systemd-tmpfiles --create --prefix /var/log/journal sudo systemctl restart systemd-journald 

Khi persistent logging enabled, future logs sẽ written to disk và retained across reboots.

The Logging Service May Not Be Running

Khả năng khác là logging service itself encountered error hoặc failed to start. Service systemd-journald responsible collect và manage log data. Nếu không running, journal naturally empty. Check status với:

systemctl status systemd-journald 

Nếu service inactive hoặc failed, restart nó sẽ restore log collection functionality.

Filters May Be Too Narrow

Đôi khi, issue không phải logs themselves, mà cách bạn access chúng. Dùng narrow filters, như non-existent unit name hoặc overly specific time range, return no results ngay cả khi relevant data exists. Thường helpful run journalctl không flags confirm logs collected, rồi progressively apply filters as needed.

Logs May Have Been Rotated hoặc Deleted

Cuối cùng, nhớ journal logs subject to size và time-based retention policies. Nếu old logs vacuumed bởi systemd-journald, không còn accessible. Inspect space journal currently using với:

journalctl --disk-usage 

Nếu configured system limit journal size aggressively, hoặc recently run vacuum command manually, logs may have been purged từ database.

2. Permission Denied khi dùng journalctl

Nếu bạn chạy journalctl as regular user và nhận "permission denied", bạn không đơn độc. Mặc định, access to system logs restricted to root user và members của group systemd-journal. Restriction này designed protect potentially sensitive log data, có thể chứa info về user activity, system processes, và service failures.

Chạy journalctl với Elevated Privileges

Giải pháp đơn giản và common nhất là chạy command với sudo. Điều này elevate privileges cho duration của command và cho phép view all system logs:

sudo journalctl 

Nếu scripting hoặc frequently inspecting logs, gõ sudo mỗi lần tedious. Trong cases đó, practical hơn permanently grant user access to journal.

Granting User Access via Group Membership

Để tránh cần sudo, add user vào group systemd-journal. Group này specially designed allow non-root users read journal logs. Add user vào group với:

sudo usermod -aG systemd-journal yourusername 

Thay thế yourusername bằng actual login name. Sau khi add user vào group, bạn phải logout và login lại cho change take effect. Sau đó, bạn nên chạy journalctl không cần elevated privileges.

Verifying Journal Permissions

Nếu group membership không resolve issue, có thể problem với file hoặc directory permissions. Directory /var/log/journal nên owned by root và grouped under systemd-journal. Group read permissions phải set correctly, hoặc access vẫn denied ngay cả khi bạn trong correct group. Fix với:

sudo chown root:systemd-journal /var/log/journal sudo chmod 2755 /var/log/journal 

Với permissions và proper group membership, non-root users access logs securely.

3. Logs Not Persisting After Reboot

Nếu notice logs disappear mỗi lần server reboot, hệ thống likely configured store logs in volatile memory only, lost khi machine power off. Đây là common default trong nhiều Linux distributions và container environments, đặc biệt optimized cho low disk usage.

Enabling Persistent Logging

Để retain logs across reboots, configure journald dùng persistent storage. Yêu cầu tạo appropriate directory nơi journal write logs to disk. Path /var/log/journal dùng cho purpose này. Nếu không exist, tạo và restart logging daemon:

sudo mkdir -p /var/log/journal sudo systemd-tmpfiles --create --prefix /var/log/journal sudo systemctl restart systemd-journald 

Sau khi done, all future logs written to disk và survive system reboots.

Verifying journald Configuration

Nếu directory exists nhưng logs vẫn không persist, worth inspect journald configuration file:

sudo nano /etc/systemd/journald.conf 

Trong file này, tìm directive Storage= dưới section [Journal]. Nếu set to volatile, change to persistent:

[Journal] Storage=persistent 

Save file và restart service apply changes. Điều này đảm bảo system sẽ write logs to disk thay vì RAM từ bây giờ.

4. Debugging Failed systemd Service

Khi systemd-managed service fails to start hoặc crashes unexpectedly, journalctl trở thành essential tool identify root cause. Thay vì search multiple log files, journal collect all messages related to service in one place, complete with metadata, timestamps, và priority levels.

Reviewing Service Status

Bước đầu troubleshooting là examine service status. Lệnh systemctl status cung cấp snapshot của service's current state, bao gồm most recent log entries. Ví dụ:

systemctl status nginx.service 

Output này thường reveal immediate issues như misconfigured paths, permission problems, hoặc exit codes. Exit code và signal information, nếu present, especially helpful determine whether service failed on its own hoặc killed by system.

Viewing Full Log History

Để xem all logs related to failed service, dùng journalctl với flag -u:

journalctl -u nginx.service 

Điều này cung cấp chronological view messages generated by service. Nếu diagnose failure happened during last system boot, helpful limit output to just that session:

journalctl -u nginx.service -b 

Investigating Failure Context

Bạn thường get to heart of issue bằng cách đọc log entries từ vài phút before và after failure. Dùng time-based filters narrow focus:

journalctl -u nginx.service --since "10 minutes ago" 

Điều này giúp identify whether problem isolated hoặc part of larger system issue.

Cho deeper analysis, enable verbose output hoặc view extended error messages dùng:

journalctl -xe 

Command này highlight priority messages và recent failures, useful khi service không leave obvious clues trong standard output.

5. Monitoring SSH Login Attempts

SSH là primary access method cho hầu hết Linux servers, cũng làm nó common vector cho brute-force attacks, unauthorized access attempts, hoặc general auditing. May mắn, journalctl cho phép monitor all SSH-related activity with ease.

Viewing SSH Logs

Systemd track SSH activity dưới unit sshd hoặc ssh, tùy distribution. Xem all entries related to SSH:

journalctl -u ssh.service 

hoặc, trên một số systems:

journalctl -u sshd.service 

Logs này bao gồm login attempts, authentication failures, session closures, và key negotiation messages. Excellent first step verify ai accessed server và khi nào.

Following SSH Activity in Real Time

Cho real-time monitoring, dùng journalctl follow mode. Especially useful nếu suspect intrusion hoặc want keep eye on active login attempts:

journalctl -f -u ssh.service 

Mỗi new login event printed live as it happens, easier spot failed logins hoặc rapid connection attempts may indicate malicious behavior.

Filtering by Login Events

Nếu looking specific login messages, như failed passwords hoặc accepted connections, filter journal output dùng keyword matches:

journalctl -u ssh.service | grep "Failed password" journalctl -u ssh.service | grep "Accepted password" 

Messages này indicate whether login successful và user nào attempted. Combine với time filters narrow search to specific window:

journalctl -u ssh.service --since "1 hour ago" 

Điều này cực helpful during security audits hoặc forensic investigations.

Frequently Asked Questions (FAQs)

1. Tại sao journalctl yêu cầu root access?

Mặc định, journalctl yêu cầu root access vì expose sensitive information collected từ system services, kernel messages, user sessions, và background daemons. Logs này có thể bao gồm usernames, environment variables, error traces, authentication attempts, và details khác pose security risk nếu accessed by unauthorized users.

Để safeguard data này, systemd restrict access to system journal. Tuy nhiên, bạn không luôn cần sudo. Non-root users read logs nếu part of systemd-journal group. Add user vào group này với:

sudo usermod -aG systemd-journal yourusername 

Sau logout và login lại, bạn nên access logs without elevated privileges, miễn file permissions trên journal directories properly configured.

2. Làm sao make logs persistent across reboots?

Để preserve logs sau reboot, configure systemd-journald dùng persistent storage thay vì volatile memory. Mặc định, một số distributions store logs trong /run/log/journal, temporary directory cleared at shutdown. Enable persistent logging:

  1. Tạo persistent journal directory:

    sudo mkdir -p /var/log/journal 
  2. Set permissions nếu cần:

    sudo systemd-tmpfiles --create --prefix /var/log/journal 
  3. Restart journal daemon:

    sudo systemctl restart systemd-journald 
  4. Optional: Verify hoặc edit configuration:

    Mở /etc/systemd/journald.conf đảm bảo line sau set:

    Storage=persistent 

Configuration này đảm bảo system retain log data across reboots, dễ dàng audit và debug historical issues.

3. Có thể clear journalctl logs không?

Có, journalctl cho phép clear logs dùng options --vacuum-* từ systemd-journald. Các commands giúp reduce disk usage bằng delete old hoặc excess log data.

Phương pháp common clear hoặc shrink journal logs:

  • Remove logs older than specific time:

    sudo journalctl --vacuum-time=2weeks 
  • Limit total disk usage cho all logs:

    sudo journalctl --vacuum-size=500M 
  • Restrict number of journal files kept:

    sudo journalctl --vacuum-files=10 

Các commands không erase current hoặc recent logs trừ khi exceed defined threshold. Để fully remove all logs, manually delete journal files từ /var/log/journal, nhưng rarely necessary và not generally recommended cho production systems.

4. Làm sao access systemd logs?

Bạn access systemd logs dùng lệnh journalctl, interface trực tiếp với systemd journal. Tất cả logs related to services managed by systemd, như boot messages, unit failures, và runtime errors, stored in journal.

Cho general access:

journalctl 

Xem logs cho specific systemd service, như nginx, dùng:

journalctl -u nginx.service 

Bạn cũng filter by boot session, priority level, time range, hoặc combine multiple services để deeper insight. Khác với traditional log files, journalctl cung cấp unified, indexed view của log messages từ multiple sources.

5. Lệnh nào dùng view systemd logs?

Primary command dùng view systemd logs là:

journalctl 

Tool này included with systemd và provides access to all logs collected by systemd-journald service, bao gồm kernel messages, early boot logs, system services, và user sessions.

Bạn tailor command với various options:

  • View logs cho specific service:

    journalctl -u ssh.service 
  • Filter logs by priority:

    journalctl -p err 
  • Display logs real time:

    journalctl -f 

Điều này làm journalctl versatile và comprehensive utility nhất view systemd-related logs.

6. Làm sao xem kernel logs qua journalctl?

Kernel messages, như traditionally viewed dùng dmesg, cũng available qua systemd journal. Display chỉ kernel messages dùng journalctl, dùng flag -k:

journalctl -k 

Command này filter output chỉ include messages originating from kernel. Especially useful diagnose hardware issues, kernel module problems, hoặc boot-time errors. Bạn cũng dùng option -b show messages từ current hoặc previous boot:

journalctl -k -b -1 

Điều này gives consistent access to kernel logs, integrated với logs từ other services cho better contextual understanding.

7. Khác biệt giữa dmesg và journalctl là gì?

Mặc dù cả dmesg và journalctl show kernel logs, chúng serve different purposes và operate under different mechanisms.

Featuredmesgjournalctl
ScopeKernel ring buffer onlyKernel + system + userland logs
PersistenceCleared on reboot hoặc buffer fullPersistent (nếu enabled)
MetadataNo structured metadataRich metadata (unit, PID, UID, etc.)
FilteringLimitedExtensive filtering capabilities
Output formatsRaw, simpleJSON, export, short, verbose, etc.
PermissionsYêu cầu sudo cho full outputYêu cầu root hoặc group membership

Tóm lại, dmesg limited to low-level kernel logs real time, trong khi journalctl offers more complete, structured, và persistent logging interface encompass entire system.

Kết luận

Như bạn thấy, systemd journal cực hữu ích collect và manage system và application data. Hầu hết flexibility đến từ extensive metadata automatically recorded và centralized nature của log.

Trong hướng dẫn này, chúng ta cover basic log viewing, time-based và field-based filtering, monitoring kernel và service logs, output formatting, và real-time log tracking. Chúng ta cũng discuss journal maintenance, storage limits, và troubleshooting common issues như missing logs hoặc permission errors.

Lệnh journalctl làm dễ dàng tận dụng advanced features của journal và làm extensive analysis và relational debugging của different application components. Bằng cách mastering journalctl, bạn gain versatile, unified logging interface cho debugging, monitoring, và auditing across entire system.

Cho detailed insight hơn vào logging và troubleshooting trên Linux systems, khám phá related tutorials sau:

  • How To Troubleshoot Common Apache Errors
  • How To Centralize Logs With Journald on Debian 10
  • How To Centralize Logs With Journald on Ubuntu 20.04

Thành thạo systemd Logs: Hướng dẫn hoàn chỉnh dùng journalctl trên LinuxBản 작업 này được cấp phép theo Giấy phép Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International.