天天看點

Linux 系統運作着許多子系統和應用程式。您可以使用系統日志記錄從啟動時就收集有關運作中系統的資料。有時

概述

在本教程中,您将學習以下内容:

  • 配置 syslog 守護程式
  • 了解标準設施、優先級和操作
  • 配置日志輪換
  • 了解 rsyslog 和 syslog-ng

系統内部發生了什麼

Linux 系統運作着許多子系統和應用程式。您可以使用系統日志記錄從啟動時就收集有關運作中系統的資料。有時,您隻需要知道一切正常就好;而有時,您會使用此資料進行審計和調試,認識到磁盤或其他資源已耗盡以及用于許多其他目的。您可以在一個系統上收集日志資料,然後将其轉發到另一系統進行處理。日志資料可以顯示在終端(例如 root 使用者的終端)上,但更多是儲存在檔案中,或通過套接字轉發到日志伺服器。毋庸置疑,日志記錄是高度可配置的。

傳統的 syslog 設施及其 syslogd 守護程式提供此日志記錄。如今,諸如 rsyslog、syslog-ng 和 systemd 日志子系統之類的其他日志記錄設施已為 syslog 提供了補充。我将在本教程中向您介紹這些設施。

本教程将幫助您為 Linux Server Professional (LPIC-1) 考試 102 的主題 108 中的目标 108.2 做好應考準備。該目标的權重為 3。

前提條件

要想最充分地利用本系列教程,您應該掌握 Linux 的基本知識,還應該有一個正常工作的 Linux 系統,您可以在這個系統上練習本教程中涵蓋的指令。您應熟悉 GNU 和 UNIX 指令。有時候,程式的不同版本将獲得不同的輸出格式,是以您的結果可能并不總是與這裡顯示的清單完全相同。

在本教程中,我将 Slackware 42.2 用于 syslogd 示例,将 CentOS 7 用于 rsyslogd 示例,将 Fedora 26 用于 systemd-journalctl 和 syslog-ng 示例。

傳統的 syslog 和 syslogd 守護程式

Linux 系統上的傳統 syslog 系統日志記錄設施提供系統日志記錄和核心消息陷阱。您可以在本地系統上記錄資料或将其發送到遠端系統。使用 /etc/syslog.conf 配置檔案可以精細控制日志記錄的級别。日志由 syslogd 守護程式進行記錄,該守護程式一般會通過 /dev/log 套接字來接收輸入,如清單 1 所示。

清單 1. /dev/log 是一個套接字
[ian@attic4-sl42 ~]$ #Slackware 42.2 [ian@attic4-sl42 ~]$ /bin/ls -l /dev/log srw-rw-rw- 1 root root 0 Nov 19 16:35 /dev/log      

顯示更多

對于本地日志記錄,主檔案通常是 /var/log/messages,但是在大多數安裝中會使用許多其他檔案,這些檔案通常位于 /var/log 目錄或其某個子目錄中。您可以全面地自定義這些選項。例如,您可能想要一個單獨的日志來記錄來自郵件系統的消息。

syslog.conf 配置檔案

syslog.conf 檔案是 syslogd 守護程式的主要配置檔案。syslog.conf 中的條目指定日志記錄規則。每個規則都有一個選擇器字段和一個操作字段,它們之間用一個或多個空格或制表符進行分隔。選擇器字段辨別該規則适用的設施和優先級,而操作字段則辨別該設施和優先級的日志記錄操作。

定義的設施包括 auth(或 security)、authpriv、cron、daemon、ftp、kern、lpr、mail、mark、news、syslog、user、uucp 以及 local0 到 local7。應該使用關鍵字 ​

​auth​

​ 代替 ​

​security​

​,關鍵字 ​

​mark​

​ 則僅供内部使用。

優先級(按照嚴重程度升序排列)如下:

  1. debug
  2. info
  3. notice
  4. warning(或 warn)
  5. err(或 error)
  6. crit
  7. alert
  8. emerg(或 panic)

現在不推薦使用括号内的關鍵字(warn、error 和 panic)。

預設行為是對指定級别和所有更進階别執行操作,但也可以将日志記錄限制為特定級别。每個選擇器都包括一個設施和一個由句點分隔的優先級。可以為一個給定操作指定多個設施,隻需用逗号分隔即可。可以為一個給定操作指定多個設施/優先級對,隻需用分号分隔即可。清單 2 給出了一個簡單的 syslog.conf 檔案示例。

清單 2. syslog.conf 示例
#Log anything 'warn' or higher.#Exclude authpriv, cron, mail, and news.These are logged elsewhere.#Don't log private authentication messages! *.warn;\ authpriv.none;cron.none;mail.none;news.none    -/var/log/syslog #The authpriv file has restricted access. authpriv.* /var/log/secure #Log all the mail messages in one place. mail.* -/var/log/maillog #Log cron stuff cron.* /var/log/cron #Everybody gets emergency messages *.emerg * #Save news errors of level crit and higher in a special file. uucp,news.crit /var/log/spooler      

注意:

  • 與許多配置檔案一樣,将忽略以 # 開頭的行和空白行。
  • 可以使用 * 來表示所有設施或所有優先級。
  • 特殊優先級關鍵字 ​

    ​none​

    ​ 表示此操作不應為此設施記錄任何日志。
  • 檔案名前的連字元(以上示例中的 -/var/log/maillog)表示在每次寫入後不應同步日志檔案。這樣做可提高性能,但系統一旦崩潰,您就可能會丢失資訊。

這些操作通常被稱為“日志檔案”,盡管它們不一定是真實檔案。表 1 描述了可能的日志檔案。

表 1. syslog.conf 中的操作
操作 目的
正常檔案 指定完整的路徑名,以斜杠 (/) 開頭。在每個日志條目之後,使用連字元 (-) 作為字首便可省略檔案同步。如果發生崩潰,這可能會導緻資訊丢失,但可以提高性能。
命名管道 使用先進先出 (FIFO),或者通過在檔案名前面包含管道符号 (|),将命名管道用作日志消息的目标。在啟動(或重新啟動)​

​syslogd</ code>之前,必須使用 mkfifo 指令建立 FIFO。FIFO 有時用于調試。​

終端或控制台 将日志消息發送到終端,例如 /dev/console。
遠端計算機 通過在主機名之前輸入 @ 符号,可将消息轉發到另一台主機。注意,消息不是從接收主機轉發的。
使用者清單 使用逗号分隔的使用者清單來接收消息(如果使用者已登入)。這裡經常包含 root 使用者。
所有登入使用者 指定一個星号(*),便可以使用 ​

​wall​

​ 指令通知所有登入使用者。

在優先級前面加上 ! 表示該操作不應适用于此級别和更進階别。類似地,在優先級前面加上 = 表示該規則僅适用于此級别,加上 != 則表示該規則适用于此級别之外的所有其他級别。清單 3 顯示了一些示例,syslog.conf 的手冊頁中還有更多示例。

清單 3. 額外的 syslog.conf 示例
#Kernel messages are first, stored in the kernel
#file, critical messages and higher ones also go
#to another host and to the console
#
kern.*                       /var/adm/kernel
kern.crit                    @log‑server
kern.crit                    /dev/console
kern.info;kern.!err          /var/adm/kernel‑info

#Store all mail messages except info priority in /var/log/mail.
mail.*;mail.!=info           /var/log/mail
      

​syslogd​

​ 指令可啟動 syslogd 守護程式。此指令有很多選項,包括:​

​-f​

​ 用于指定一個不同的配置檔案,​

​-a​

​ 則表示要偵聽的其他套接字。守護程式會響應幾個信号,包括 SIGHUP(可重新初始化守護程式)。有關運作 syslogd 守護程式和與之互動的更多詳細資訊,可參見手冊或資訊頁。

清單 4 顯示了一些可能使用 ​

​syslogd​

​ 配置參數(如清單 2 所示)記錄到 /var/log/messages 的消息。

清單 4. /var/log/messages 中記錄的消息示例
root@attic4‑sl42:~#tail ‑n 20 /var/log/messages     
Nov 19 21:39:57 attic4‑sl42 kernel: [ 1403.274747] usb 1‑1.1: New USB device strings: Mfr=1, Product=2, SerialNumber=3
Nov 19 21:39:57 attic4‑sl42 kernel: [ 1403.274751] usb 1‑1.1: Product: USB DISK 2.0
Nov 19 21:39:57 attic4‑sl42 kernel: [ 1403.274755] usb 1‑1.1: Manufacturer:         
Nov 19 21:39:57 attic4‑sl42 kernel: [ 1403.274759] usb 1‑1.1: SerialNumber: 070B53DF11FC0170
Nov 19 21:39:57 attic4‑sl42 kernel: [ 1403.275036] usb‑storage 1‑1.1:1.0: USB Mass Storage device detected
Nov 19 21:39:57 attic4‑sl42 kernel: [ 1403.275801] scsi host12: usb‑storage 1‑1.1:1.0
Nov 19 21:39:57 attic4‑sl42 mtp‑probe: checking bus 1, device 12: "/sys/devices/pci0000:00/0000:00:12.2/usb1/1‑1/1‑1.1" 
Nov 19 21:39:57 attic4‑sl42 mtp‑probe: bus: 1, device: 12 was not an MTP device 
Nov 19 21:39:58 attic4‑sl42 kernel: [ 1404.301570] scsi 12:0:0:0: Direct‑Access              USB DISK 2.0     PMAP PQ: 0 ANSI: 4
Nov 19 21:39:59 attic4‑sl42 kernel: [ 1405.651626] sd 12:0:0:0: [sdd] 30299520 512‑byte logical blocks: (15.5 GB/14.4 GiB)
Nov 19 21:39:59 attic4‑sl42 kernel: [ 1405.652236] sd 12:0:0:0: [sdd] Write Protect is off
Nov 19 21:40:00 attic4‑sl42 kernel: [ 1405.678810]  sdd: sdd1
Nov 19 21:40:00 attic4‑sl42 kernel: [ 1405.683911] sd 12:0:0:0: [sdd] Attached SCSI removable disk
Nov 19 21:42:36 attic4‑sl42 kernel: [ 1562.844117] usb 1‑1.1: reset high‑speed USB device number 12 using ehci‑pci
Nov 19 21:42:37 attic4‑sl42 kernel: [ 1563.044142] usb 1‑1.1: reset high‑speed USB device number 12 using ehci‑pci
Nov 19 21:42:37 attic4‑sl42 kernel: [ 1563.245138] usb 1‑1.1: reset high‑speed USB device number 12 using ehci‑pci
Nov 19 21:42:37 attic4‑sl42 kernel: [ 1563.619154] usb 1‑1.1: reset high‑speed USB device number 12 using ehci‑pci
Nov 19 21:42:38 attic4‑sl42 kernel: [ 1563.919798] usb 1‑1.1: USB disconnect, device number 12
Nov 19 21:42:38 attic4‑sl42 kernel: <27>[ 1563.950967] udevd[3540]: inotify_add_watch(6, /dev/sdd, 10) failed: No such file or directory
Nov 19 21:56:48 attic4‑sl42 ‑‑ MARK ‑‑
      

核心日志守護程式 – klogd

在清單 3 中,您看到了用于配置核心消息日志記錄的一些方法。但是,甚至在安裝檔案系統之前,核心消息是如何記錄啟動時的呢?核心會将消息存儲在記憶體的環形緩沖區中。​

​klogd​

​ 守護程式将直接處理這些消息,傳遞至控制台或 /var/log/dmesg 之類的檔案中,或通過 syslog 設施來處理。

注意,清單 2 中的示例将警告級别或更進階别的消息都記錄在 /var/log/syslog 中。尤其是,這包括核心消息。

與 ​

​syslogd​

​ 指令一樣,​

​klogd​

​ 指令也有許多選項。有關詳細資訊,參見手冊頁或資訊頁。​

​klogd​

​ 沒有配置檔案。

您也可以使用 ​

​dmesg​

​ 指令顯示來自核心環形緩沖區的消息。該指令還具有與環形緩沖區進行互動的選項,例如,讀取和清除消息。

日志檔案的輪換和歸檔

​logrotate​

​ 指令的基本思路是定期備份日志檔案并啟動新日志。保留了幾代日志,當日志老化到最後一代時,便會将其歸檔。例如,可能會通過郵件将其發送給歸檔使用者。

使用 /etc/logrotate.conf 配置檔案來指定日志的輪換和歸檔方式。您可以為不同的日志檔案指定不同的頻率(例如每天、每周或每月),并且還可以控制要維護的代數以及何時或是否通過郵件将副本發送給歸檔使用者。清單 5 顯示了一個 /etc/logrotate.conf 檔案樣本。

清單 5. /etc/logrotate.conf 樣本
#/etc/logrotate.conf ##logrotate is designed to ease administration of systems that generate large #numbers of log files.It allows automatic rotation, compression, removal, and #mailing of log files.Each log file may be handled daily, weekly, monthly, or #when it grows too large.##logrotate is normally run daily from root's crontab.##For more details, see "man logrotate".#rotate log files weekly: weekly #keep 4 weeks worth of backlogs: rotate 4 #create new (empty) log files after rotating old ones: create #uncomment if you want to use the date as a suffix of the rotated file #dateext #uncomment this if you want your log files compressed: #compress #some packages install log rotation information in this directory: include /etc/logrotate.d #Rotate /var/log/wtmp: /var/log/wtmp { missingok monthly create 0664 root utmp minsize 1M rotate 1 } #Rotate /var/log/btmp: /var/log/btmp { missingok monthly create 0600 root root rotate 1 } #Note that /var/log/lastlog is not rotated.This is intentional, and it should #not be.The lastlog file is a database, and is also a sparse file that takes #up much less space on the drive than it appears.#system-specific logs may be also be configured below:      

logrotate.conf 檔案開頭包含全局選項。如果沒有在其他地方指定更具體的内容,則這些是預設選項。在此示例中,日志檔案每周輪換一次,并且保留了四個星期的備份。輪換日志檔案後,将自動建立一個新日志檔案來代替舊日志檔案。注意,logrotate.conf 檔案可能包含來自其他檔案的規範。這裡包含了 /etc/logrotate.d 中的所有檔案。

此示例還包括 /var/log/wtmp 和 /var/log/btmp 的特定規則,也就是每月輪換一次。如果檔案丢失,系統不會發出錯誤消息。系統将建立一個新檔案,并且僅維護一個備份。通過設定權限,也可以限制對這些檔案的通路。

注意:檔案 /var/log/wtmp 和 /var/log/btmp 分别記錄了成功和失敗的登入嘗試。與大多數日志檔案不同,這些并不是明确的文本檔案。您可以使用 ​

​last​

​ 或 ​

​lastb​

​ 指令來檢查這些檔案。有關這些指令的詳細資訊,可參見手冊頁。

在此示例中,當備份達到最後一代時,由于沒有說明要如何處理備份,是以将其删除。

當日志檔案達到特定大小時,您可以對其進行備份。您還可以編寫在備份操作之前或之後運作的指令腳本。清單 6 顯示了一個更複雜的示例。

清單 6. 另一個 logrotate 配置示例
/var/log/messages { rotate 5 mail logsave@log-server size 100k postrotate /usr/bin/killall -HUP syslogd endscript }      

在清單 6 中,/var/log/messages 在達到 100 KB 之後就開始輪換了。維護了五個備份檔案,當最早的備份過期時,會通過郵件将其發送到 logsave@log-server。​

​postrotate​

​ 引入了一個腳本,用于在輪換完成後通過向 syslogd 守護程式發送 HUP 信号将其重新啟動。要終止此腳本,就需要使用 ​

​endscript​

​ 語句;如果存在 ​

​prerotate​

​ 腳本,也需要使用此語句。有關更完整資訊,可參見 logrotate 手冊頁。

與許多此類配置檔案一樣,某些程式通常在 etc/logrotate.d 目錄中提供了附加配置。清單 7 顯示了我的 Slackware 系統上的檔案。

清單 7. logrotate 的配置檔案
root@attic4‑sl42:~#ls /etc/logrot
/etc/logrotate.conf

/etc/logrotate.d:
consolekit  mcelog  mysql.orig  ulogd   wpa_supplicant
httpd       mysql   syslog      vsftpd
root@attic4‑sl42:~#cat /etc/logrotate.d/httpd
/var/log/httpd/_log {
  rotate 10
  notifempty
  missingok
  size=5M
  compress
  delaycompress
  sharedscripts
  postrotate
    /etc/rc.d/rc.httpd restart
  endscript
}
      

掃描日志檔案以發現值得注意的活動

日志檔案條目通常帶有時間戳,并包含報告程序的主機名以及程序名稱。清單 8 顯示了 /var/log/messages 中的幾行,其中包含來自多個程式的條目。

清單 8. 日志檔案條目樣本
Nov 19 15:48:31 attic4-sl42 kernel: [ 7.407406] EXT4-fs (sda6): re-mounted.Opts: (null) Nov 19 15:48:32 attic4-sl42 mtp-probe: checking bus 3, device 3: "/sys/devices/pci0000:00/0000:00:12.0/usb3/3-2/3-2.1" Nov 19 15:48:32 attic4-sl42 mtp-probe: bus: 3, device: 3 was not an MTP device Nov 19 15:48:32 attic4-sl42 mtp-probe: checking bus 3, device 4: "/sys/devices/pci0000:00/0000:00:12.0/usb3/3-2/3-2.4" Nov 19 15:48:32 attic4-sl42 mtp-probe: bus: 3, device: 4 was not an MTP device Nov 19 15:48:32 attic4-sl42 mtp-probe: checking bus 1, device 4: "/sys/devices/pci0000:00/0000:00:12.2/usb1/1-1/1-1.1" Nov 19 15:48:32 attic4-sl42 mtp-probe: bus: 1, device: 4 was not an MTP device Nov 19 15:48:36 attic4-sl42 root: /etc/rc.d/rc.inet1: /sbin/ifconfig lo 127.0.0.1 Nov 19 15:48:36 attic4-sl42 root: /etc/rc.d/rc.inet1: /sbin/route add -net 127.0.0.0 netmask 255.0.0.0 lo Nov 19 15:48:36 attic4-sl42 root: /etc/rc.d/rc.inet1: /sbin/dhcpcd -t 10 eth0 Nov 19 15:48:36 attic4-sl42 dhcpcd[1112]: eth0: adding address fe80::4c2a:3f48:e0f7:cc90 Nov 19 15:48:41 attic4-sl42 sshd[1255]: Server listening on 0.0.0.0 port 22.Nov 19 15:48:41 attic4-sl42 sshd[1255]: Server listening on :: port 22.Nov 19 15:48:41 attic4-sl42 ntpd[1262]: ntpd [email protected] Fri Jun 3 23:08: 22 UTC 2016 (1): Starting Nov 19 15:48:41 attic4-sl42 ntpd[1262]: Command line: /usr/sbin/ntpd -g -p /var /run/ntpd.pid Nov 19 15:48:41 attic4-sl42 ntpd[1264]: proto: precision = 0.230 usec (-22) Nov 19 15:48:41 attic4-sl42 ntpd[1264]: Listen and drop on 0 v6wildcard [::]:12 3 Nov 19 15:48:41 attic4-sl42 ntpd[1264]: Listen and drop on 1 v4wildcard 0.0.0.0:123 Nov 19 15:48:41 attic4-sl42 ntpd[1264]: Listen normally on 2 lo 127.0.0.1:123 Nov 19 15:48:41 attic4-sl42 ntpd[1264]: Listen normally on 3 eth0 192.168.1.24:123 Nov 19 15:48:41 attic4-sl42 ntpd[1264]: Listen normally on 4 lo [::1]:123 Nov 19 15:48:41 attic4-sl42 ntpd[1264]: failed to init interface for address fe80::8616:f9ff:fe04:7a2a%2 Nov 19 15:48:41 attic4-sl42 ntpd[1264]: Listening on routing socket on fd #21 for interface updates Nov 19 15:48:41 attic4-sl42 acpid: starting up with netlink and the input layer Nov 19 15:48:41 attic4-sl42 acpid: 1 rule loaded Nov 19 15:48:41 attic4-sl42 acpid: waiting for events: event logging is off Nov 19 15:48:42 attic4-sl42 dbus[1226]: [system] Activating service name='org.freedesktop.PolicyKit1' (using servicehelper) Nov 19 15:48:42 attic4-sl42 ntpd[1264]: failed to init interface for address fe80::8616:f9ff:fe04:7a2a%2      

清單 8 的最後一行表明 Network Time Protocol 守護程式 (ntpd) 失敗。在這種情況下,無法初始化 IP V6 接口,因為該系統僅使用 IP V4 連接配接。

您可以使用諸如 ​

​less​

​ 之類的尋呼機來掃描日志檔案,或者使用 ​

​grep​

​ 來搜尋特定條目(例如,來自主機 attic4-sl42 的 ntpd 消息),如清單 9 所示。

清單 9. 掃描日志檔案
root@attic4-sl42:~#grep "attic4-sl42 ntpd" /var/log/messages | tail -9 Nov 19 21:17:12 attic4-sl42 ntpd[1131]: Command line: /usr/sbin/ntpd -g -p /var/run/ntpd.pid Nov 19 21:17:12 attic4-sl42 ntpd[1133]: proto: precision = 0.220 usec (-22) Nov 19 21:17:13 attic4-sl42 ntpd[1133]: Listen and drop on 0 v6wildcard [::]:123 Nov 19 21:17:13 attic4-sl42 ntpd[1133]: Listen and drop on 1 v4wildcard 0.0.0.0:123 Nov 19 21:17:13 attic4-sl42 ntpd[1133]: Listen normally on 2 lo 127.0.0.1:123 Nov 19 21:17:13 attic4-sl42 ntpd[1133]: Listen normally on 3 eth0 192.168.1.24:123 Nov 19 21:17:13 attic4-sl42 ntpd[1133]: Listen normally on 4 lo [::1]:123 Nov 19 21:17:13 attic4-sl42 ntpd[1133]: Listen normally on 5 eth0 [fe80::8616:f9ff:fe04:7a2a%2]:123 Nov 19 21:17:13 attic4-sl42 ntpd[1133]: Listening on routing socket on fd #22 for interface updates      

監控日志檔案

有時,您可能需要監控日志檔案以發現某些事件。例如,您可能正在嘗試捕獲不經常發生的事件。在這種情況下,可以使用帶有 -f 選項的 ​

​tail​

​ 指令來跟蹤日志檔案。清單 10 給出了一個示例。

清單 10. 後續日志檔案更新
root@attic4-sl42:~#tail -n 1 -f /var/log/messages Nov 20 09:24:58 attic4-sl42 kernel: [43705.563240] sd 15:0:0:0: [sdd] Attached SCSI removable disk Nov 20 09:26:23 attic4-sl42 kernel: [43790.820125] usb 3-2.4: USB disconnect, device number 5 Nov 20 09:27:13 attic4-sl42 sshd[6059]: Accepted password for ian from 192.168.1.40 port 58184 ssh2 Nov 20 09:29:08 attic4-sl42 kernel: [43955.890670] usb 3-2.4: new low-speed USB device number 6 using ohci-pci Nov 20 09:29:08 attic4-sl42 kernel: [43955.989492] usb 3-2.4: New USB device found, idVendor=046d, idProduct=c50e Nov 20 09:29:08 attic4-sl42 kernel: [43955.989501] usb 3-2.4: New USB device strings: Mfr=1, Product=2, SerialNumber=0 Nov 20 09:29:08 attic4-sl42 kernel: [43955.989506] usb 3-2.4: Product: USB Receiver Nov 20 09:29:08 attic4-sl42 kernel: [43955.989509] usb 3-2.4: Manufacturer: Logitech Nov 20 09:29:08 attic4-sl42 kernel: [43956.003175] input: Logitech USB Receiver as /devices/pci0000:00/0000:00:12.0/usb3/3-2/3-2.4/3-2.4:1.0/0003:046D:C50E.0004/input/input19 Nov 20 09:29:08 attic4-sl42 kernel: [43956.054049] hid-generic 0003:046D:C50E.0004: input,hidraw1: USB HID v1.11 Mouse [Logitech USB Receiver] on usb-0000:00:12.0-2.4/input0 Nov 20 09:29:08 attic4-sl42 mtp-probe: checking bus 3, device 6: "/sys/devices/pci0000:00/0000:00:12.0/usb3/3-2/3-2.4" Nov 20 9:29:08 attic4-sl42 mtp-probe: bus: 3, device: 6 was not an MTP device      

跟蹤日志檔案中報告的問題

在日志檔案中發現問題時,記下時間、主機名以及産生問題的程序。如果該消息足夠明确地辨別了問題以便您解決,那麼您的工作便已完成。否則的話,可能需要更新 syslog.conf 來指定相應設施來記錄更多消息。例如,您可能需要顯示參考消息,而不是警告消息乃至調試級别的消息。您的應用程式可能具有其他可以使用的設施。

最後,如果您需要在日志檔案中設定标記以幫助您了解在調試活動的哪個階段記錄了哪些消息,您可以從終端視窗使用 ​

​logger​

​ 指令或者使用 Shell 腳本,将您選擇的消息發送給 syslogd 守護程式,以便根據 syslog.conf 中的規則進行日志記錄。

使用 rsyslogd

Rsyslog 是用于日志處理的自我描述系統,速度極快。它可以從 syslog 向上相容,因為它可以處理與 syslog 相容的配置,還可以處理對日志資訊的 syslog 調用。它還提供了一些增強功能,但這些增強功能無法向後相容。尤其是,它支援其他日志記錄協定,并且可以記錄到資料庫(例如 MySQL 或 PostgreSQL)以及檔案中。您可以過濾 syslog 消息的任何部分,也可以完全配置輸出格式。

傳統的手冊頁和資訊頁提供了有關 rsyslog 的基本資訊。但是,系統的 doc 目錄中有大量 HTML 格式的文檔。如果您的系統中未安裝 rsyslog-doc 包,則可能需要進行安裝。HTML 樹的根目錄位于 /usr/share/doc/rsyslog-8.24.0/html/index.html。該位置在您的系統上可能會有所不同。

​rsyslog​

​ 程式作為守護程式運作,類似于 ​

​syslogd​

​。配置檔案預設為 rsyslog.conf。

清單 11. rsyslog.conf 配置檔案
[ian@attic4‑ce7 ~]$ cat /etc/rsyslog.conf 
#rsyslog configuration file

#For more information see /usr/share/doc/rsyslog‑*/rsyslog_conf.html
#If you experience problems, see https://www.rsyslog.com/doc/v8-stable/troubleshooting/index.html####MODULES ####

#The imjournal module bellow is now used as a message source instead of imuxsock.
$ModLoad imuxsock #provides support for local system logging (e.g. via logger command)
$ModLoad imjournal #provides access to the systemd journal
#$ModLoad imklog #reads kernel messages (the same are read from journald)
#$ModLoad immark  #provides ‑‑MARK‑‑ message capability

#Provides UDP syslog reception
#$ModLoad imudp
#$UDPServerRun 514

#Provides TCP syslog reception
#$ModLoad imtcp
#$InputTCPServerRun 514


####GLOBAL DIRECTIVES ####

#Where to place auxiliary files
$WorkDirectory /var/lib/rsyslog

#Use default timestamp format
$ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat

#File syncing capability is disabled by default.This feature is usually not required,
#not useful and an extreme performance hit
#$ActionFileEnableSync on

#Include all config files in /etc/rsyslog.d/
$IncludeConfig /etc/rsyslog.d/.conf

#Turn off message reception via local log socket;
#local messages are retrieved through imjournal now.
$OmitLocalLogging on

#File to store the position in the journal
$IMJournalStateFile imjournal.state


####RULES ####

#Log all kernel messages to the console.
#Logging much else clutters up the screen.
#kern./dev/console

#Log anything (except mail) of level info or higher.
#Don't log private authentication messages!
.info;mail.none;authpriv.none;cron.none                /var/log/messages

#The authpriv file has restricted access.
authpriv./var/log/secure

#Log all the mail messages in one place.
mail.‑/var/log/maillog


#Log cron stuff
cron./var/log/cron

#Everybody gets emergency messages
.emerg                                                 :omusrmsg:

#Save news errors of level crit and higher in a special file.
uucp,news.crit                                          /var/log/spooler

#Save boot messages also to boot.log
local7./var/log/boot.log


####begin forwarding rule ###
#The statement between the begin ... end define a SINGLE forwarding
#rule.They belong together, do NOT split them.If you create multiple
#forwarding rules, duplicate the whole block!
#Remote Logging (we use TCP for reliable delivery)
#
#An on‑disk queue is created for this action.If the remote host is
#down, messages are spooled to disk and sent when it is up again.
#$ActionQueueFileName fwdRule1 #unique name prefix for spool files
#$ActionQueueMaxDiskSpace 1g   #1gb space limit (use as much as possible)
#$ActionQueueSaveOnShutdown on #save messages to disk on shutdown
#$ActionQueueType LinkedList   #run asynchronously
#$ActionResumeRetryCount ‑1    #infinite retries if host is down
#remote host is: name/ip:port, e.g. 192.168.0.1:514, port optional
#.*`  remote‑host:514
####end of the forwarding rule ###
      

您将在檔案中間看到熟悉的 syslog.conf 條目,其中包含 rsyslog 設施可以了解的其他内容。有關更多詳細資訊,可參見手冊頁、資訊頁或 HTML 文檔。

您可以将 ​

​logrotate​

​ 與 ​

​rsyslogd​

​ 建立的檔案一起使用,但 SQL 資料庫可能需要腳本或其他工具。同樣地,​

​logger​

​ 指令仍然可以在日志中設定您自己的标記。

使用 systemd 日志服務

本節中的 systemd 日志服務示例來自 Fedora 26。

​systemd-journald​

​ 程式是一個系統服務守護程式,用于收集和存儲日志資料。它基于從 syslog 常見來源接收的日志記錄資訊以及使用本機日志 API 的結構化日志消息,建立和維護結構化的索引日志。

一般的 /dev/log 套接字是指向 /run/systemd/journal/dev-log 的連結,如清單 12 中所示。

清單 12. dev/log 和 /run/systemd/journal/dev-log 套接字
[root@atticf26 ~]#ls ‑l /dev/log
lrwxrwxrwx.1 root root 28 Nov 20 23:43 /dev/log ‑> /run/systemd/journal/dev‑log
[root@atticf26 ~]#ls ‑l /run/systemd/journal/dev‑log
srw‑rw‑rw‑.1 root root 0 Nov 20 23:43 /run/systemd/journal/dev‑log
      

systemd-journald 守護程式會偵聽套接字和其他檔案系統實體,包括 /dev/kmsg、/dev/log、/run/systemd/journal/dev-log、/run/systemd/journal/socket 和 /run/systemd/journal/stdout。它還可以使用 netlink 偵聽審計事件,使用套接字将核心資訊傳輸到使用者空間。

大多數日志資料都是文本資料,但允許二進制資料,理論上最大為 2^ 64-1 個位元組。預設情況下,日志将日志資料存儲在 /run/log/journal/ 中。/run/ 檔案系統是易失性的,是以在系統重新開機後,日志資料會丢失。為了持久存儲資料,可建立 /var/log/journal/,然後 systemd-journald 會将資料存儲在此處。

與其他日志記錄系統一樣,這裡有一個配置檔案。預設為 /etc/systemd/journald.conf。預設情況下會編譯很多選項,是以配置檔案中的大多數選項最初都會被注釋掉,如清單 13 所示。取消注釋您要更改的内容。通常,其他配置檔案可能位于 journald.conf.d 目錄中。軟體包應該在 /usr/lib/systemd/*.conf.d/ 中安裝其日志配置資訊。

清單 13. 初始 /etc/systemd/journald.conf 示例
# This file is part of systemd.
#
# systemd is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
#Entries in this file show the compile time defaults.
#You can change settings by editing this file.
#Defaults can be restored by simply deleting this file.
#
#See journald.conf(5) for details.

[Journal]
#Storage=auto
#Compress=yes
#Seal=yes
#SplitMode=uid
#SyncIntervalSec=5m
#RateLimitIntervalSec=30s
#RateLimitBurst=1000
#SystemMaxUse=
#SystemKeepFree=
#SystemMaxFileSize=
#SystemMaxFiles=100
#RuntimeMaxUse=
#RuntimeKeepFree=
#RuntimeMaxFileSize=
#RuntimeMaxFiles=100
#MaxRetentionSec=
#MaxFileSec=1month
#ForwardToSyslog=no
#ForwardToKMsg=no
#ForwardToConsole=no
#ForwardToWall=yes
#TTYPath=/dev/console
#MaxLevelStore=debug
#MaxLevelSyslog=debug
#MaxLevelKMsg=notice
#MaxLevelConsole=info
#MaxLevelWall=emerg
      

使用 journald.conf 的手冊頁或資訊頁,了解有關受支援配置設定的更多資訊。

使用 ​

​journalctl​

​ 指令顯示記錄的資訊。清單 14 表明了如何顯示已記錄資料的最後 10 行,然後使用 ​

​-f​

​ 選項跟蹤或連續顯示所添加的新行。使用 ​

​--rotate​

​ 選項可輪換日志檔案。

清單 14. 使用 journalctl 顯示或跟蹤日志消息
[root@atticf26 ~]#journalctl ‑n 10 ‑f
‑‑ Logs begin at Mon 2007‑07‑09 22:14:00 EDT.‑‑
Nov 21 10:24:47 atticf26 dbus‑daemon[585]: [system] Activating via systemd: service name='org.freedesktop.nm_dispatcher' unit='dbus‑org.freedesktop.nm‑dispatcher.service' requested by ':1.9' (uid=0 pid=650 comm="/usr/sbin/NetworkManager ‑‑no‑daemon " label="system_u:system_r:NetworkManager_t:s0")
Nov 21 10:24:47 atticf26 systemd[1]: Starting Network Manager Script Dispatcher Service...
Nov 21 10:24:47 atticf26 audit[1]: SERVICE_START pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=NetworkManager‑dispatcher comm="systemd" exe="/usr/lib/systemd/systemd" hostname=? addr=? terminal=? res=success'
Nov 21 10:24:47 atticf26 dbus‑daemon[585]: [system] Successfully activated service 'org.freedesktop.nm_dispatcher'
Nov 21 10:24:47 atticf26 systemd[1]: Started Network Manager Script Dispatcher Service.
Nov 21 10:24:47 atticf26 nm‑dispatcher[7121]: req:1 'connectivity‑change': new request (5 scripts)
Nov 21 10:24:47 atticf26 nm‑dispatcher[7121]: req:1 'connectivity‑change': start running ordered scripts...
Nov 21 10:24:48 atticf26 gnome‑software‑service.desktop[4641]: 15:24:48:0034 Gs  failed to call gs_plugin_app_install on packagekit: do not know how to install app in state queued
Nov 21 10:24:52 atticf26 dhclient[7110]: DHCPDISCOVER on enp4s0 to 255.255.255.255 port 67 interval 15 (xid=0x36565033)
Nov 21 10:24:57 atticf26 audit[1]: SERVICE_STOP pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=NetworkManager‑dispatcher comm="systemd" exe="/usr/lib/systemd/systemd" hostname=? addr=? terminal=? res=success'
Nov 21 10:25:07 atticf26 dhclient[7110]: DHCPDISCOVER on enp4s0 to 255.255.255.255 port 67 interval 14 (xid=0x36565033)
Nov 21 10:25:21 atticf26 dhclient[7110]: DHCPDISCOVER on enp4s0 to 255.255.255.255 port 67 interval 17 (xid=0x36565033)
Nov 21 10:25:22 atticf26 NetworkManager[650]: <warn>  [1511277922.0280] dhcp4 (enp4s0): request timed out
Nov 21 10:25:22 atticf26 NetworkManager[650]: <info>  [1511277922.0286] dhcp4 (enp4s0): state changed unknown ‑> timeout
Nov 21 10:25:22 atticf26 NetworkManager[650]: <info>  [1511277922.0380] dhcp4 (enp4s0): canceled DHCP transaction, DHCP client pid 7110
Nov 21 10:25:22 atticf26 NetworkManager[650]: <info>  [1511277922.0381] dhcp4 (enp4s0): state changed timeout ‑> done
Nov 21 10:25:22 atticf26 NetworkManager[650]: <info>  [1511277922.0386] device (enp4s0): state change: ip‑config ‑> failed (reason 'ip‑config‑unavailable', internal state 'managed')
Nov 21 10:25:22 atticf26 NetworkManager[650]: <warn>  [1511277922.0393] device (enp4s0): Activation: failed for connection 'enp3s0'
Nov 21 10:25:22 atticf26 NetworkManager[650]: <info>  [1511277922.0401] device (enp4s0): state change: failed ‑> disconnected (reason 'none', internal state 'managed')

...

Nov 21 10:26:37 atticf26 NetworkManager[650]: <info>  [1511277997.7805] device (enp4s0): state change: ip‑config ‑> deactivating (reason 'user‑requested', internal state 'managed')
Nov 21 10:26:37 atticf26 NetworkManager[650]: <info>  [1511277997.7811] audit: op="device‑disconnect" interface="enp4s0" ifindex=3 pid=7167 uid=1000 result="success"
Nov 21 10:26:37 atticf26 NetworkManager[650]: <info>  [1511277997.7817] device (enp4s0): state change: deactivating ‑> disconnected (reason 'user‑requested', internal state 'managed')
Nov 21 10:26:37 atticf26 gnome‑software‑service.desktop[4641]: 15:26:37:0783 Gs  failed to call gs_plugin_app_install on packagekit: do not know how to install app in state queued
Nov 21 10:26:37 atticf26 avahi‑daemon[602]: Withdrawing address record for fe80::3fd7:76aa:e99d:da5d on enp4s0.
Nov 21 10:26:37 atticf26 avahi‑daemon[602]: Leaving mDNS multicast group on interface enp4s0.IPv6 with address fe80::3fd7:76aa:e99d:da5d.
Nov 21 10:26:37 atticf26 avahi‑daemon[602]: Interface enp4s0.IPv6 no longer relevant for mDNS.
Nov 21 10:26:37 atticf26 gnome‑software‑service.desktop[4641]: 15:26:37:0787 Gs  failed to call gs_plugin_app_install on packagekit: do not know how to install app in state queued
Nov 21 10:26:37 atticf26 NetworkManager[650]: <info>  [1511277997.7993] dhcp4 (enp4s0): canceled DHCP transaction, DHCP client pid 7179
Nov 21 10:26:37 atticf26 NetworkManager[650]: <info>  [1511277997.7993] dhcp4 (enp4s0): state changed unknown ‑> done
Nov 21 10:26:37 atticf26 audit: NETFILTER_CFG table=filter family=2 entries=99
Nov 21 10:26:37 atticf26 audit: NETFILTER_CFG table=nat family=2 entries=59
Nov 21 10:26:37 atticf26 audit: NETFILTER_CFG table=mangle family=2 entries=42
Nov 21 10:26:37 atticf26 audit: NETFILTER_CFG table=raw family=2 entries=30
Nov 21 10:26:37 atticf26 dbus‑daemon[585]: [system] Activating via systemd: service name='org.freedesktop.nm_dispatcher' unit='dbus‑org.freedesktop.nm‑dispatcher.service' requested by ':1.9' (uid=0 pid=650 comm="/usr/sbin/NetworkManager ‑‑no‑daemon " label="system_u:system_r:NetworkManager_t:s0")
Nov 21 10:26:37 atticf26 systemd[1]: Starting Network Manager Script Dispatcher Service...
Nov 21 10:26:37 atticf26 audit: NETFILTER_CFG table=filter family=10 entries=90
Nov 21 10:26:37 atticf26 audit: NETFILTER_CFG table=nat family=10 entries=54
Nov 21 10:26:37 atticf26 audit: NETFILTER_CFG table=mangle family=10 entries=41
Nov 21 10:26:37 atticf26 audit: NETFILTER_CFG table=raw family=10 entries=31
Nov 21 10:26:37 atticf26 dbus‑daemon[585]: [system] Successfully activated service 'org.freedesktop.nm_dispatcher'
Nov 21 10:26:37 atticf26 audit[1]: SERVICE_START pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=NetworkManager‑dispatcher comm="systemd" exe="/usr/lib/systemd/systemd" hostname=? addr=? terminal=? res=success'
Nov 21 10:26:37 atticf26 nm‑dispatcher[7223]: req:1 'down' [enp4s0]: new request (5 scripts)
Nov 21 10:26:37 atticf26 systemd[1]: Started Network Manager Script Dispatcher Service.
Nov 21 10:26:37 atticf26 nm‑dispatcher[7223]: req:1 'down' [enp4s0]: start running ordered scripts...
Nov 21 10:26:38 atticf26 gnome‑software‑service.desktop[4641]: 15:26:38:0787 Gs  failed to call gs_plugin_app_install on packagekit: do not know how to install app in state queued
Nov 21 10:26:48 atticf26 audit[1]: SERVICE_STOP pid=1 uid=0 auid=4294967295 ses=4294967295 subj=system_u:system_r:init_t:s0 msg='unit=NetworkManager‑dispatcher comm="systemd" exe="/usr/lib/systemd/systemd" hostname=? addr=? terminal=? res=success'
Nov 21 10:28:35 atticf26 cupsd[4544]: REQUEST localhost ‑ ‑ "POST / HTTP/1.1" 200 182 Renew‑Subscription successful‑ok
      

​systemctl​

​ 指令可顯示有關守護程式和相關單元的資訊,并可與之互動或對其加以控制。清單 15 給出了一個示例。

清單 15. 使用 systemctl 指令
[root@atticf26 ~]#systemctl  list‑units "journal" ‑‑no‑pager
UNIT                            LOAD   ACTIVE SUB     DESCRIPTION              
abrt‑journal‑core.service       loaded active running Creates ABRT problems fro
systemd‑journal‑flush.service   loaded active exited  Flush Journal to Persiste
systemd‑journald.service        loaded active running Journal Service          
systemd‑journald‑audit.socket   loaded active running Journal Audit Socket     
systemd‑journald‑dev‑log.socket loaded active running Journal Socket (/dev/log)
systemd‑journald.socket         loaded active running Journal Socket           

LOAD   = Reflects whether the unit definition was properly loaded.
ACTIVE = The high‑level unit activation state, i.e. generalization of SUB.
SUB    = The low‑level unit activation state, values depend on unit type.

6 loaded units listed.Pass ‑‑all to see loaded but inactive units, too.
To show all installed unit files use 'systemctl list‑unit‑files'.
      

使用 syslog-ng

Syslog-ng 對自己的描述是“增強的日志守護程式,支援多種輸入和輸出方法:syslog、非結構化文本、隊列、SQL 和 NoSQL”。它支援遺留和增強的 syslog 協定,并增加了對 JavaScript 對象表示法 (JSON) 和 journald 消息格式的支援。Syslog-ng 支援使用廣泛的功能來過濾輸入和格式化輸出。

安裝後,手冊頁和資訊頁中會提供基本資訊。不過,您可能想要使用《syslog-ng 開源版本管理者指南》,該指南以 HTML 和 PDF 格式提供。(有關更多資訊,可參見右側的資源)。

預設配置檔案是 /etc/syslog-ng/syslog-ng.conf。清單 16 中顯示了一個示例。其他配置檔案可能位于 /etc/syslog-ng/conf.d 目錄中。

清單 16. syslog-ng.conf 示例
@version:3.9
@include "scl.conf"

#syslog‑ng configuration file.
#
#This should behave pretty much like the original syslog on RedHat.But
#it could be configured a lot smarter.
#
#See syslog‑ng(8) and syslog‑ng.conf(5) for more information.
#
#Note: it also sources additional configuration files (*.conf)
#      located in /etc/syslog‑ng/conf.d/

options {
    flush_lines (0);
    time_reopen (10);
    log_fifo_size (1000);
    chain_hostnames (off);
    use_dns (no);
    use_fqdn (no);
    create_dirs (no);
    keep_hostname (yes);
};

source s_sys {
    system();
    internal();
    #udp(ip(0.0.0.0) port(514));
};

destination d_cons { file("/dev/console"); };
destination d_mesg { file("/var/log/messages"); };
destination d_auth { file("/var/log/secure"); };
destination d_mail { file("/var/log/maillog" flush_lines(10)); };
destination d_spol { file("/var/log/spooler"); };
destination d_boot { file("/var/log/boot.log"); };
destination d_cron { file("/var/log/cron"); };
destination d_kern { file("/var/log/kern"); };
destination d_mlal { usertty(""); };

filter f_kernel     { facility(kern); };
filter f_default    { level(info..emerg) and
                        not (facility(mail)
                        or facility(authpriv) 
                        or facility(cron)); };
filter f_auth       { facility(authpriv); };
filter f_mail       { facility(mail); };
filter f_emergency  { level(emerg); };
filter f_news       { facility(uucp) or
                        (facility(news) 
                        and level(crit..emerg)); };
filter f_boot   { facility(local7); };
filter f_cron   { facility(cron); };

#log { source(s_sys); filter(f_kernel); destination(d_cons); };
log { source(s_sys); filter(f_kernel); destination(d_kern); };
log { source(s_sys); filter(f_default); destination(d_mesg); };
log { source(s_sys); filter(f_auth); destination(d_auth); };
log { source(s_sys); filter(f_mail); destination(d_mail); };
log { source(s_sys); filter(f_emergency); destination(d_mlal); };
log { source(s_sys); filter(f_news); destination(d_spol); };
log { source(s_sys); filter(f_boot); destination(d_boot); };
log { source(s_sys); filter(f_cron); destination(d_cron); };


#Source additional configuration files (.conf extension only)
@include "/etc/syslog‑ng/conf.d/.conf"


#vim:ft=syslog‑ng:ai:si:ts=4:sw=4:et:
      

繼續閱讀