บทนำสู่ systemd Journal และ journalctl Logging
ข้อได้เปรียบที่น่าสนใจที่สุดของ systemd บางอย่างเกี่ยวข้องกับ process และ system logging เมื่อใช้ tools อื่น logs มักกระจายทั่วระบบ จัดการโดย daemons และ processes ต่างๆ และยากต่อการตีความเมื่อครอบคลุมหลาย applications systemd พยายามแก้ปัญหาเหล่านี้ด้วย centralized management solution สำหรับ logging ทุก kernel และ userland processes ระบบที่ collect และ manage logs เรียกว่า journal
Journal implemented ด้วย journald daemon ซึ่งจัดการ messages ทั้งหมดที่ผลิตโดย kernel, initrd, services ฯลฯ ในคู่มือนี้ เราจะพูดถึงการใช้ journalctl utility ซึ่งใช้ access และ manipulate data ที่เก็บใน journal
ในบทความนี้ คุณจะเรียนรู้ใช้คำสั่ง journalctl command-line tool เพื่อ access และ filter log data จาก systemd journal เราจะครอบคลุมการ view logs จาก specific boots หรือ time ranges filter by systemd units, users, หรือ priority levels และ output logs ใน formats อย่าง JSON สำหรับ integration กับ tools อื่น คุณยังเรียนรู้ monitor real-time events จัดการ disk usage configure persistent logging และแก้ common issues เช่น missing logs หรือ permission errors ไม่ว่าคุณจะ debug failing service หรือ setup centralized log collection journalctl ให้ flexibility และ precision ที่ streamline workflow ของคุณ
สรุปสำคัญ (Key Takeaways)
systemdjournal ให้ unified logging system ที่ capture messages จาก kernel, services, และ user applications ใน centralized, indexed log เดียว- คำสั่ง
journalctlให้ filter logs by boot sessions, time ranges, systemd units, process IDs, user IDs, group IDs และอื่นๆ ทำให้ pinpoint relevant events ง่าย - ดึง logs จาก specific time windows ได้ด้วย options เช่น
--since,--untilหรือ relative expressions อย่าง"1 hour ago"หรือ"yesterday" - Logs แสดงใน formats ต่างๆ เช่น plain text, JSON, verbose mode ทำให้ integrate กับ external tools หรือ parse สำหรับ analysis ง่าย
- ใช้
journalctl -ffollow log messages live ขณะเขียน คล้ายtail -fuseful สำหรับ monitor system activity หรือ service behavior real-time - By default logs อาจเก็บใน memory และหายเมื่อ reboot คุณ enable persistent logging ได้โดยสร้าง
/var/log/journalและ configjournald.confตามนั้น - Journal's storage footprint จัดการได้ด้วย commands อย่าง
--disk-usage,--vacuum-size,--vacuum-timeรวมถึง config options ควบคุม max size และ retention journalctlทำให้ service debugging ง่ายด้วยการ aggregate logs across boots และ units ทำให้ identify failures, track SSH access, และ investigate issues พร้อม detailed context ง่ายขึ้น
systemd Journal ทำงานอย่างไร และทำไมมันสำคัญ
หนึ่งใน impetuses หลัง systemd journal คือ centralize management ของ logs ไม่ว่าจะมาจากไหน เนื่องจาก boot process และ service management ส่วนใหญ่ handled by systemd process จึงสมเหตุสมผลที่จะ standardize วิธี collect และ access logs journald daemon collect data จาก all available sources และ store ใน binary format เพื่อ easy และ dynamic manipulation
นี่ให้ significant advantages หลายอย่าง โดย interact กับ data ด้วย single utility administrators สามารถ dynamically display log data ตาม needs ได้ อาจ simple เป็น view boot data จาก three boots ago หรือ combine log entries sequentially จาก two related services เพื่อ debug communication issue
Store log data ใน binary format ยังหมายถึง data แสดงใน arbitrary output formats ได้ ขึ้นอยู่กับสิ่งที่คุณต้องการตอนนั้น ตัวอย่าง daily log management คุณเคย view logs ใน standard syslog format แต่ถ้าตัดสินใจ graph service interruptions ภายหลัง คุณ output each entry as JSON object ทำให้ consumable โดย graphing service เนื่องจาก data ไม่ได้ written to disk ใน plain text ไม่ต้อง convert เมื่อต้องการ different on-demand format
systemd journal ใช้ร่วมกับ existing syslog implementation ได้ หรือ replace syslog functionality ขึ้นอยู่กับ needs ของคุณ ในขณะที่ systemd journal ครอบคลุม logging needs ของ admin ส่วนใหญ่ มันยัง complement existing logging mechanisms ได้ ตัวอย่าง คุณอาจมี centralized syslog server compile data จาก multiple servers แต่ก็อยาก interleave logs จาก multiple services บน single system ด้วย systemd journal คุณทำทั้งสองอย่างได้โดย combine technologies
ตั้งค่า System Time ให้ถูกต้องด้วย timedatectl
ข้อได้เปรียมของ binary journal สำหรับ logging คือ view log records ใน UTC หรือ local time ตามต้องการ By default systemd แสดง results ใน local time
เพราะฉะนั้น ก่อนเริ่ม journal เราจะ ensure timezone setup ถูกต้อง systemd suite มี tool ชื่อ timedatectl ช่วยเรื่องนี้
ก่อน ดู timezones ที่ available ด้วย option list-timezones:
timedatectl list-timezones
จะ list timezones available บนระบบของคุณ เมื่อเจอ timezone ที่ match location ของ server คุณ set ด้วย option set-timezone:
sudo timedatectl set-timezone zone
ให้แน่ใจว่า machine ใช้เวลาถูกต้องตอนนี้ ใช้ timedatectl command เพียงอย่างเดียว หรือพร้อม option status display เหมือนกัน:
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
บรรทัดแรกควรแสดงเวลาที่ถูกต้อง
ดู Logs ด้วย journalctl
ดู logs ที่ journald daemon collect ใช้คำสั่ง journalctl
ใช้เพียงอย่างเดียว ทุก journal entry ในระบบจะแสดงใน pager (โดยปกติ less) ให้ browse entries เก่าสุดอยู่บนสุด:
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 . . .
คุณน่าจะมี pages และ pages ของ data scroll through ซึ่งอาจยาวสิบๆ ถึงร้อยๆ พันบรรทัดถ้า systemd อยู่บนระบบนาน นี่แสดงว่ามี data มากแค่ไหนใน journal database
Format คุ้นเคยสำหรับคนชิน standard syslog logging แต่จริงๆ collect data จาก sources มากกว่า traditional syslog implementations รวม logs จาก early boot process, kernel, initrd, และ application standard error และ out ทั้งหมด available ใน journal
คุณอาจสังเกต timestamps ทั้งหมดเป็น local time นี่ available สำหรับทุก log entry ตอนนี้เรา set local time ถูกต้องบนระบบแล้ว Logs ทั้งหมดแสดงด้วยข้อมูลใหม่นี้
ถ้าอยาก display timestamps ใน UTC ใช้ flag --utc:
journalctl --utc
Filter systemd Logs ตามเวลา ด้วย journalctl
การเข้าถึง large collection ของ data useful แต่ information จำนวนมาก difficult หรือ impossible inspect และ process manually เพราะฉะนั้น important feature หนึ่งของ journalctl คือ filtering options
Show Logs จาก Current Boot Session ด้วย journalctl
Basic filter ที่คุณอาจใช้ daily คือ flag -b จะ show all journal entries ที่ collected since most recent reboot
journalctl -b
ช่วย identify และ manage information pertinent to current environment
ในกรณีไม่ใช้ feature นี้ และ display มากกว่า one day of boots คุณจะเห็น journalctl inserted line 长这样 whenever system went down:
. . . -- Reboot -- . . .
นี่ใช้ logically separate information เป็น boot sessions ได้
เข้าถึง Logs จาก Previous Boots ใช้ journalctl
แม้คุณจะ commonly อยาก display information จาก current boot แต่แน่นอนมีครั้งที่ past boots helpful จะ journal save information จาก many previous boots ได้ ดังนั้น journalctl ทำให้ display information easily
บาง distributions enable saving previous boot information by default อื่นๆ disable feature นี้ เพื่อ enable persistent boot information คุณสร้าง directory store journal:
sudo mkdir -p /var/log/journal
หรือ edit journal configuration file:
sudo nano /etc/systemd/journald.conf
Under [Journal] section set Storage= option เป็น "persistent" เพื่อ enable persistent logging:
/etc/systemd/journald.conf
. . . [Journal] Storage=persistent
เมื่อ saving previous boots enabled บน server journalctl ให้ commands ช่วย work with boots as a unit of division ดู boots ที่ journald รู้จัก ใช้ option --list-boots กับ 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
แสดง line สำหรับแต่ละ boot คอลัมน์แรกคือ offset สำหรับ boot ใช้ reference กับ journalctl ได้ง่าย ถ้าต้องการ absolute reference boot ID ในคอลัมน์ที่สอง คุณบอกเวลา boot session ได้จาก two time specifications ท้าย
Display information จาก boots นี้ ใช้ information จากคอลัมน์แรกหรือสอง
เช่น ดู journal จาก previous boot ใช้ -1 relative pointer กับ flag -b:
journalctl -b -1
คุณยังใช้ boot ID เรียก data จาก boot ได้:
journalctl -b caf0524a1d394ce0bdbcff75b94444fe
Filter journalctl Logs ด้วย Custom Date และ Time Ranges
เห็น log entries by boot useful แต่ often คุณอาจ request time windows ที่ไม่ align กับ system boots โดยเฉพาะ long-running servers กับ significant uptime
Filter by arbitrary time limits 用 options --since และ --until restrict entries displayed ให้หลังหรือก่อน given time ตามลำดับ
Time values มีหลาย formats สำหรับ absolute time values ใช้ format:
YYYY-MM-DD HH:MM:SS
เช่น ดู all entries since January 10th, 2015 at 5:15 PM:
journalctl --since "2015-01-10 17:15:00"
ถ้า components ของ format ข้างบนละเลย defaults จะ applied ถ้า date omitted current date assumed ถ้า time component missing "00:00:00" (midnight) substituted seconds field เลิกได้ default "00":
journalctl --since "2015-01-10" --until "2015-01-11 03:00"
Journal เข้าใจ relative values และ named shortcuts บางอย่าง เช่น "yesterday", "today", "tomorrow", "now" Relative times โดย prepend "-" หรือ "+" กับ numbered value หรือใช้ words อย่าง "ago" ใน sentence construction
ได้ data จาก yesterday พิมพ์:
journalctl --since yesterday
ถ้าได้ reports service interruption เริ่ม 9:00 AM ถึง an hour ago พิมพ์:
journalctl --since 09:00 --until "1 hour ago"
เห็นได้ define flexible windows of time filter entries ที่อยากดู straightforward
Filter systemd Journal Logs by Service, PID, หรือ User
ข้างต้นเราเรียนรู้ filter journal data 用 time constraints ในส่วนนี้ discuss filter based on service หรือ component ที่สนใจ systemd journal ให้ ways หลากหลาย
View Logs by Systemd Service Unit
Most useful way filter คือ by unit ที่สนใจ ใช้ option -u filter วิธีนี้
เช่น ดู all logs จาก Nginx unit บนระบบ พิมพ์:
journalctl -u nginx.service
Typically คุณอาจอยาก filter by time ด้วย display lines ที่สนใจ เช่น check service running today พิมพ์:
journalctl -u nginx.service --since today
Focus นี้ extremely helpful เมื่อใช้ journal's ability interleave records จาก various units ตัวอย่าง Nginx process connected to PHP-FPM unit process dynamic content คุณ merge entries จาก both ใน chronological order โดย specify both units:
journalctl -u nginx.service -u php-fpm.service --since today
นี่ทำให้ spot interactions ระหว่าง different programs และ debug systems แทน individual processes ง่ายกว่ามาก
Filter systemd Logs by PID, UID, หรือ GID
บาง services spawn child processes หลากหลาย ถ้าคุณ scouted exact PID ของ process ที่สนใจ filter by that ได้
ทำได้โดย specify field _PID เช่น PID ที่สนใจคือ 8088 พิมพ์:
journalctl _PID=8088
บางครั้งอยาก show all entries logged จาก specific user หรือ group ทำได้ด้วย filters _UID หรือ _GID เช่น web server รัน under www-data user หา user ID:
id -u www-data
33
ต่อมา ใช้ ID ที่คืนมา filter journal results:
journalctl _UID=33 --since today
systemd journal มี fields หลายอย่าง untuk filtering บางอย่าง passed from process being logged บางอย่าง applied by journald 用 info gathered from system at log time
Leading underscore บ่งชี้ _PID field เป็น latter type Journal automatically records และ indexes PID ของ process logging สำหรับ filtering ภายหลัง หา available journal fields ทั้งหมดพิมพ์:
man systemd.journal-fields
เราจะ discuss บางอย่างในคู่มือนี้ ตอนนี้ไป over one more useful option ทำ filtering by these fields Option -F ใช้ show all available values สำหรับ given journal field
เช่น ดู group IDs ที่ systemd journal มี entries พิมพ์:
journalctl -F _GID
32 99 102 133 81 84 100 0 124 87
แสดง all values ที่ journal stored สำหรับ group ID field ช่วย construct filters ของคุณ
View Logs by Executable Path
เรา filter ได้ด้วยการ provide path location
ถ้า path นำไป executable journalctl display all entries involve executable นั้น เช่น หา entries involve bash executable พิมพ์:
journalctl /usr/bin/bash
ปกติถ้ามี unit สำหรับ executable วิธีนั้น cleaner และให้ better info (entries จาก associated child processes ฯลฯ) แต่บางครั้งไม่ possible
ดู Kernel Logs ใช้ journalctl -k
Kernel messages ที่มักอยู่ใน dmesg output ดึงจาก journal ได้
Display only these messages เพิ่ม flags -k หรือ --dmesg:
journalctl -k
By default display kernel messages จาก current boot ระบุ alternative boot 用 normal boot selection flags ที่ discussed previously เช่น ดู messages จาก five boots ago พิมพ์:
journalctl -k -b -5
Filter Logs by Severity Level ด้วย journalctl -p
Filter ที่ system administrators มักสนใจคือ message priority ในขณะที่ log information at very verbose level useful ตอน digest available information low priority logs อาจ distracting และ confusing
ใช้ journalctl display only messages ของ specified priority หรือ above 用 option -p filter out lower priority messages
เช่น show only entries logged at error level หรือ above พิมพ์:
journalctl -p err -b
แสดง all messages marked as error, critical, alert, หรือ emergency Journal implement standard syslog message levels ใช้ priority name หรือ numeric value ได้ ในลำดับ highest to lowest priority:
- 0: emerg
- 1: alert
- 2: crit
- 3: err
- 4: warning
- 5: notice
- 6: info
- 7: debug
ตัวเลขหรือชื่อด้านบน interchangeable กับ option -p Select priority จะ display messages marked at specified level และ those above it
Customize journalctl Log Output Display
ข้างต้น demonstrate entry selection through filtering มี ways อื่น modify output เรา adjust journalctl display fit various needs
Control Output Length และ Formatting ใน journalctl
เรา adjust จะ journalctl displays data โดยบอก shrink หรือ expand output
By default journalctl show entire entry in pager allowing entries trail off right of screen info นี้ access ได้โดยกด right arrow key
ถ้าอยาก output truncated inserting ellipsis ที่ information removed ใช้ 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
คุณไป opposite direction ได้ บอก journalctl display all information regardless unprintable characters ด้วย flag -a:
journalctl -a
Disable Pager ใน journalctl Output
By default journalctl displays output in pager สำหรับ easier consumption ถ้าคุณ plan process data with text manipulation tools อย่างไรก็ตาม คุณอาจอยาก output to standard output
ทำได้ด้วย option --no-pager:
journalctl --no-pager
Pipe immediately into processing utility หรือ redirect into file on disk ขึ้นอยู่กับ needs
Different Output Formats ใน journalctl
ถ้าคุณ processing journal entries ตามที่กล่าว ข้างต้น likely easier parse data ถ้าใน consumable format ที่ดีกว่า Luckily journal displayed 在 variety of formats as needed 用 option -o with format specifier
เช่น output journal entries ใน JSON พิมพ์:
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" } . . .
มีประโยชน์สำหรับ parsing with utilities คุณใช้ format json-pretty ได้ handle data structure ดีก่อน pass ให้ 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" } . . .
Formats ต่อไปใช้ display ได้:
- cat: แสดง message field เองอย่างเดียว
- export: Binary format suitable for transferring หรือ backing up
- json: Standard JSON with one entry per line
- json-pretty: JSON formatted for better human-readability
- json-sse: JSON formatted output wrapped make add server-sent event compatible
- short: Default
syslogstyle output - short-iso: Default format augmented show ISO 8601 wallclock timestamps
- short-monotonic: Default format with monotonic timestamps
- short-precise: Default format with microsecond precision
- verbose: Shows every journal field available for entry รวม those usually hidden internally
Options เหล่านี้ให้ display journal entries ใน format ที่ suit current needs ของคุณ
Monitor Live systemd Logs ด้วย journalctl
คำสั่ง journalctl imitate วิธีที่หลาย admins ใช้ tail monitor active หรือ recent activity Functionality นี้ built into journalctl ให้ access features นี้โดยไม่ต้อง pipe ไป tool อื่น
Show Recent Log Entries ด้วย journalctl -n
Display set amount of records 用 option -n works exactly as tail -n
By default display most recent 10 entries:
journalctl -n
ระบุ number of entries ที่อยากเห็น ด้วย number after -n:
journalctl -n 20
Follow Real-Time Logs ด้วย journalctl -f
Actively follow logs ขณะเขียน ใช้ flag -f อีกครั้ง works as you might expect ถ้ามี experience 用 tail -f:
journalctl -f
ออกจากคำสั่งนี้ พิมพ์ CTRL+C
จัดการและ Clean Up systemd Journal Logs
คุณอาจ wonder เกี่ยวกับ cost ของ storing all data ที่เห็น จะ interesting clean up older logs และ free up space
Check Disk Usage ของ systemd Logs ด้วย journalctl --disk-usage
หา amount of space journal currently occupying on disk 用 flag --disk-usage:
journalctl --disk-usage
Archived and active journals take up 8.0M in the file system.
Delete Old Logs ด้วย journalctl --vacuum-size และ --vacuum-time
ถ้าอยาก shrink journal ทำได้ two ways (available with systemd version 218 และ later)
用 --vacuum-size option shrink journal โดย indicate size จะ remove old entries จน total journal space taken up on disk at requested size:
sudo journalctl --vacuum-size=1G
อีก way shrink journal คือ provide cutoff time with --vacuum-time option Entries beyond that time deleted ทำให้ keep entries created after specific time
เช่น keep entries จาก last year พิมพ์:
sudo journalctl --vacuum-time=1years
Configure Disk Space Limits สำหรับ Journald Logs
Config server place limits space journal can take up โดย edit /etc/systemd/journald.conf file
Items ต่อไป limit journal growth:
SystemMaxUse=: ระบุ maximum disk space used by journal in persistent storageSystemKeepFree=: ระบุ space journal should leave free when adding journal entries to persistent storageSystemMaxFileSize=: Controls how large individual journal files grow in persistent storage before rotatedRuntimeMaxUse=: ระบุ maximum disk space used in volatile storage (within/runfilesystem)RuntimeKeepFree=: ระบุ space set aside for other uses when writing data to volatile storage (within/runfilesystem)RuntimeMaxFileSize=: ระบุ space individual journal file takes up in volatile storage (within/runfilesystem) before rotated
Setting these values คุณ control journald consumes และ preserves space บน server จำไว้ SystemMaxFileSize และ RuntimeMaxFileSize target archived files to reach stated limits สำคัญตอน interpret file counts after vacuuming operation
Troubleshooting Common journalctl และ systemd Journal Issues
1. ทำไม journalctl ไม่แสดง Logs?
บางกรณี คุณรัน journalctl คาดหวัง log output แต่เจอ blank screen หรือ no meaningful results สถานการณ์นี้ confusing โดยเฉพาะตอน troubleshoot issue หรือหา recent system activity แต่มี common explanations หลายอย่าง demystify ทำไม journalctl ไม่แสดง logs
Journal Database ว่างหรือ Missing
Straightforward reason 看到 no output คือ journal ว่าง เกิดบน newly installed systems, minimal container environments, หรือ servers ที่ system logging ยังไม่ generate entries อาจเป็นไปได้ระบบ configured store logs only in memory (volatile storage) หมายถึง all logs erased on reboot เพื่อ check persistent logging enabled ดู presence of journal directory:
ls /var/log/journal
ถ้า directory ไม่อยู่ หรือว่าง หมายถึง logs ไม่ saved between boots Resolve โดยสร้าง directory และ restart journald service:
sudo mkdir -p /var/log/journal sudo systemd-tmpfiles --create --prefix /var/log/journal sudo systemctl restart systemd-journald
เมื่อ persistent logging enabled future logs จะ written to disk และ retained across reboots
Logging Service อาจไม่ Running
อีก possibility logging service itself encountered error หรือ failed to start systemd-journald service responsible collect และ manage log data ถ้าไม่ running journal จะว่างเปล่า Check status:
systemctl status systemd-journald
ถ้า service inactive หรือ failed restart ควร restore log collection functionality
Filters อาจ Narrow เกินไป
บางครั้ง issue ไม่ได้กับ logs แต่กับวิธี access ใช้ narrow filters เช่น non-existent unit name หรือ overly specific time range สามารถ return no results แม้ relevant data exists มัก helpful run journalctl without flags confirm logs collected แล้ว progressively apply filters as needed
Logs อาจ Rotated หรือ Deleted
สุดท้าย จดไว้ journal logs subject to size และ time-based retention policies ถ้า old logs vacuumed by systemd-journald จะไม่ accessible อีกแล้ว Inspect space journal currently using:
journalctl --disk-usage
ถ้าคุณ config system limit journal size aggressively หรือ run vacuum command manually 近期 logs may have been purged from database
2. Permission Denied ตอนใช้ journalctl
ถ้าพยายามรัน journalctl as regular user ได้ "permission denied" คุณไม่ได้คนเดียว By default access to system logs restricted to root user และ members of systemd-journal group Restriction นี้ designed protect potentially sensitive log data ซึ่งอาจมี info about user activity, system processes, service failures
รัน journalctl with Elevated Privileges
Simplest และ most common solution รัน command with sudo Elevate privileges สำหรับ duration of command ให้ view all system logs:
sudo journalctl
ถ้า scripting หรือ frequently inspect logs พิมพ์ sudo ทุกครั้ง tedious ในกรณีแบบนี้ permanently grant user access to journal practical กว่า
Grant User Access ผ่าน Group Membership
หลีกเลี่ยง sudo เพิ่ม user เข้า systemd-journal group Group นี้ designed allow non-root users read journal logs เพิ่ม user เข้า group:
sudo usermod -aG systemd-journal yourusername
Replace yourusername ด้วย actual login name หลังเพิ่ม user เข้า group ต้อง log out and log back in ให้ change take effect ทำแล้วควร run journalctl โดยไม่ต้อง elevated privileges
Verifying Journal Permissions
ถ้า group membership ไม่ resolve issue อาจมีปัญหา file หรือ directory permissions /var/log/journal directory ควร owned by root grouped under systemd-journal Group read permissions ต้อง set ถูกต้อง ไม่งั้น access denied แม้ใน correct group Fix:
sudo chown root:systemd-journal /var/log/journal sudo chmod 2755 /var/log/journal
With these permissions และ proper group membership non-root users access logs securely
3. Logs Not Persisting หลัง Reboot
ถ้าสังเกต logs disappear ทุกครั้ง server reboot ระบบ likely configured store logs in volatile memory only lost when machine powers off Common default ในหลาย Linux distributions และ container environments โดยเฉพาะ optimized for low disk usage
Enabling Persistent Logging
Retain logs across reboots configure journald use persistent storage ต้อง create appropriate directory journal write logs to disk Path /var/log/journal used for this purpose ถ้าไม่ exist สร้างและ restart logging daemon:
sudo mkdir -p /var/log/journal sudo systemd-tmpfiles --create --prefix /var/log/journal sudo systemctl restart systemd-journald
หลังทำแล้ว future logs written to disk และ survive system reboots
Verifying journald Configuration
ถ้า directory exists แต่ logs ยังไม่ persist inspect journald configuration file:
sudo nano /etc/systemd/journald.conf
ใน file หา directive Storage= under [Journal] section ถ้า set to volatile เปลี่ยนเป็น persistent:
[Journal] Storage=persistent
Save file และ restart service apply changes นี่ ensure system write logs to disk แทน RAM จากนี้ไป
4. Debugging a Failed systemd Service
ตอน systemd-managed service fails to start หรือ crashes unexpectedly journalctl กลายเป็น essential tool identify root cause แทน search multiple log files journal collects all messages related to service in one place complete with metadata, timestamps, priority levels
Reviewing the Service Status
First step troubleshooting examine service status systemctl status ให้ snapshot ของ service's current state รวม most recent log entries ตัวอย่าง:
systemctl status nginx.service
Output often reveals immediate issues เช่น misconfigured paths, permission problems, exit codes Exit code และ signal information ถ้ามี helpful determine service failed on its own หรือ killed by system
Viewing the Full Log History
ดู all logs related to failed service 用 journalctl with -u flag:
journalctl -u nginx.service
ให้ chronological view of messages generated by service ถ้าพยายาม diagnose failure happened during last system boot helpful limit output to just that session:
journalctl -u nginx.service -b
Investigating Failure Context
บ่อยครั้งได้ heart of issue โดยอ่าน log entries จาก few minutes before และ after failure 用 time-based filters narrow focus:
journalctl -u nginx.service --since "10 minutes ago"
ช่วย identify problem isolated หรือ part of larger system issue
Deeper analysis enable verbose output หรือ view extended error messages 用:
journalctl -xe
คำสั่งนี้ highlight priority messages และ recent failures useful ตอน service ไม่留 obvious clues ใน standard output
5. Monitoring SSH Login Attempts
SSH เป็น primary access method สำหรับ Linux servers ส่วนใหญ่ ทำให้มัน common vector for brute-force attacks, unauthorized access attempts, หรือ general auditing Fortunately journalctl ให้ monitor all SSH-related activity easily
Viewing SSH Logs
Systemd tracks SSH activity under sshd หรือ ssh unit ขึ้นอยู่กับ distribution ดู all entries related to SSH:
journalctl -u ssh.service
หรือบนบางระบบ:
journalctl -u sshd.service
Logs รวม login attempts, authentication failures, session closures, key negotiation messages Excellent first step verify who accessed server และ when
Following SSH Activity in Real Time
Real-time monitoring 用 journalctl in follow mode โดยเฉพาะ useful ถ้าคุณ suspect intrusion หรืออยากดู active login attempts:
journalctl -f -u ssh.service
Each new login event printed live as it happens ทำให้ spot failed logins หรือ rapid connection attempts ที่อาจ indicate malicious behavior ง่ายขึ้น
Filtering by Login Events
ถ้าหา specific login messages เช่น failed passwords หรือ accepted connections filter journal output 用 keyword matches:
journalctl -u ssh.service | grep "Failed password" journalctl -u ssh.service | grep "Accepted password"
Messages นี้ indicate login successful หรือไม่ และ user ไหน attempted Combine with time filters narrow search to specific window:
journalctl -u ssh.service --since "1 hour ago"
นี่ extremely helpful during security audits หรือ forensic investigations
Frequently Asked Questions (FAQs)
1. ทำไม journalctl ต้องการ root access?
By default journalctl ต้องการ root access เพราะ expose sensitive information collected from system services, kernel messages, user sessions, และ background daemons Logs เหล่านี้อาจมี usernames, environment variables, error traces, authentication attempts, และ details อื่นๆ ที่อาจเป็น security risk ถ้า accessed by unauthorized users
Safeguard data systemd restrict access to system journal แต่คุณไม่ต้องใช้ sudo เสมอไป Non-root users read logs ได้ถ้าเป็น part of systemd-journal group เพิ่ม user เข้า group:
sudo usermod -aG systemd-journal yourusername
หลัง log out และ back in คุณควร access logs without elevated privileges ตราบใดที่ file permissions on journal directories configured properly
2. ทำไงให้ logs persistent across reboots?
Preserve logs after reboot configure systemd-journald use persistent storage แทน volatile memory By default some distributions store logs in /run/log/journal temporary directory cleared at shutdown Enable persistent logging:
Create persistent journal directory:
sudo mkdir -p /var/log/journalSet permissions if needed:
sudo systemd-tmpfiles --create --prefix /var/log/journalRestart journal daemon:
sudo systemctl restart systemd-journaldOptional: Verify or edit configuration:
Open
/etc/systemd/journald.confensure following line set:Storage=persistent
Configuration นี้ ensure system retain log data across reboots ทำให้ audit และ debug historical issues ง่ายขึ้น
3. ฉัน clear journalctl logs ได้ไหม?
ได้ journalctl allows clear logs 用 --vacuum-* options provided by systemd-journald Commands นี้ช่วย reduce disk usage โดย delete old หรือ excess log data
Common methods clear หรือ shrink journal logs:
Remove logs older than specific time:
sudo journalctl --vacuum-time=2weeksLimit total disk usage for all logs:
sudo journalctl --vacuum-size=500MRestrict number of journal files kept:
sudo journalctl --vacuum-files=10
Commands นี้ไม่ erase current หรือ recent logs เว้นแต่ exceed defined threshold เพื่อ fully remove all logs คุณ manual delete journal files จาก /var/log/journal แต่ rarely necessary และไม่ generally recommended for production systems
4. เข้าถึง systemd logs ยังไง?
เข้าถึง systemd logs 用คำสั่ง journalctl ซึ่ง interface directly with systemd journal All logs related to services managed by systemd เช่น boot messages, unit failures, runtime errors stored in journal
For general access:
journalctl
ดู logs for specific systemd service เช่น nginx 用:
journalctl -u nginx.service
คุณ filter by boot session, priority level, time range หรือ combine multiple services เพื่อ deeper insight ได้ ไม่เหมือน traditional log files journalctl ให้ unified, indexed view of log messages from multiple sources
5. คำสั่งไหนใช้ view systemd logs?
Primary command used view systemd logs คือ:
journalctl
Tool นี้ included with systemd ให้ access all logs collected by systemd-journald service รวม kernel messages, early boot logs, system services, และ user sessions
Tailor command with various options:
View logs for a specific service:
journalctl -u ssh.serviceFilter logs by priority:
journalctl -p errDisplay logs in real time:
journalctl -f
นี่ทำให้ journalctl versatile และ comprehensive utility สำหรับ view systemd-related logs
6. ดู kernel logs ผ่าน journalctl ยังไง?
Kernel messages เช่นที่ traditionally view 用 dmesg available through systemd journal Display only kernel messages 用 journalctl 用 flag -k:
journalctl -k
คำสั่งนี้ filter output include only messages originating from kernel มีประโยชน์ diagnose hardware issues, kernel module problems, หรือ boot-time errors ใช้ -b option show messages from current หรือ previous boot:
journalctl -k -b -1
ให้ consistent access to kernel logs integrated with logs from other services for better contextual understanding
7. ความแตกต่างระหว่าง dmesg และ journalctl คืออะไร?
ทั้ง dmesg และ journalctl show kernel logs ได้ แต่ serve different purposes และ operate under different mechanisms
| Feature | dmesg | journalctl |
|---|---|---|
| Scope | Kernel ring buffer only | Kernel + system + userland logs |
| Persistence | Cleared on reboot or buffer full | Persistent (if enabled) |
| Metadata | No structured metadata | Rich metadata (unit, PID, UID, etc.) |
| Filtering | Limited | Extensive filtering capabilities |
| Output formats | Raw, simple | JSON, export, short, verbose, etc. |
| Permissions | Requires sudo for full output | Requires root or group membership |
สรุป dmesg limited to low-level kernel logs real-time ในขณะที่ journalctl ให้ more complete, structured, และ persistent logging interface ที่ encompass entire system
สรุป
เห็นได้ systemd journal incredibly useful สำหรับ collect และ manage system และ application data ส่วนใหญ่ flexibility มาจาก extensive metadata automatically recorded และ centralized nature of the log
ในคู่มือนี้ เราครอบคลุม basic log viewing, time-based และ field-based filtering, monitoring kernel และ service logs, output formatting, และ real-time log tracking เราพูดถึง journal maintenance, storage limits, และ troubleshooting common issues เช่น missing logs หรือ permission errors
คำสั่ง journalctl ทำให้ easy take advantage of advanced features of journal และ do extensive analysis และ relational debugging of different application components โดย mastering journalctl คุณได้ versatile, unified logging interface สำหรับ debugging, monitoring, และ auditing across entire system
สำหรับ detailed insight logging และ troubleshooting on Linux systems สำรวจ related tutorials:
- 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
งานนี้ได้รับอนุญาตภายใต้ Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.