linux+应用程序运行日志,Linux 系统运行着许多子系统和应用程序。您可以使用系统日志记录从启动时就收集有关运行中系统的数据。有时...

概述

在本教程中,您将学习以下内容:

配置 syslog 守护程序

了解标准设施、优先级和操作

配置日志轮换

了解 rsyslog 和 syslog-ng

系统内部发生了什么

Linux 系统运行着许多子系统和应用程序。您可以使用系统日志记录从启动时就收集有关运行中系统的数据。有时,您只需要知道一切正常就好;而有时,您会使用此数据进行审计和调试,认识到磁盘或其他资源已耗尽以及用于许多其他目的。您可以在一个系统上收集日志数据,然后将其转发到另一系统进行处理。日志数据可以显示在终端(例如 root 用户的终端)上,但更多是保存在文件中,或通过套接字转发到日志服务器。毋庸置疑,日志记录是高度可配置的。

关于本系列教程

参阅“学习 Linux 101:LPIC-1 学习路线图”,获得本系列中每个教程的简介和链接。这个路线图正在完善中,反映了 2015 年 4 月 15 日更新的 LPIC-1 V4.0 考试目标。在教程完成后,会将它们添加到路线图中。

传统的 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 则仅供内部使用。

优先级(按照严重程度升序排列)如下:

debug

info

notice

warning(或 warn)

err(或 error)

crit

alert

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 命令完成的,通常作为 cron 作业运行。(有关 cron 作业的更多信息,参见我们的教程通过安排作业自动化处理系统管理任务。)

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 4.2.8p8@1.3265-o 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]: [1511277922.0280] dhcp4 (enp4s0): request timed out

Nov 21 10:25:22 atticf26 NetworkManager[650]: [1511277922.0286] dhcp4 (enp4s0): state changed unknown ‑> timeout

Nov 21 10:25:22 atticf26 NetworkManager[650]: [1511277922.0380] dhcp4 (enp4s0): canceled DHCP transaction, DHCP client pid 7110

Nov 21 10:25:22 atticf26 NetworkManager[650]: [1511277922.0381] dhcp4 (enp4s0): state changed timeout ‑> done

Nov 21 10:25:22 atticf26 NetworkManager[650]: [1511277922.0386] device (enp4s0): state change: ip‑config ‑> failed (reason 'ip‑config‑unavailable', internal state 'managed')

Nov 21 10:25:22 atticf26 NetworkManager[650]: [1511277922.0393] device (enp4s0): Activation: failed for connection 'enp3s0'

Nov 21 10:25:22 atticf26 NetworkManager[650]: [1511277922.0401] device (enp4s0): state change: failed ‑> disconnected (reason 'none', internal state 'managed')

...

Nov 21 10:26:37 atticf26 NetworkManager[650]: [1511277997.7805] device (enp4s0): state change: ip‑config ‑> deactivating (reason 'user‑requested', internal state 'managed')

Nov 21 10:26:37 atticf26 NetworkManager[650]: [1511277997.7811] audit: op="device‑disconnect" interface="enp4s0" ifindex=3 pid=7167 uid=1000 result="success"

Nov 21 10:26:37 atticf26 NetworkManager[650]: [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]: [1511277997.7993] dhcp4 (enp4s0): canceled DHCP transaction, DHCP client pid 7179

Nov 21 10:26:37 atticf26 NetworkManager[650]: [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:

显示更多

通常,您不必同时运行 systemd 日志和 syslog-ng 日志。若希望同时使用这两者,就需要对它们的配置进行一些更改,然后重新启动这两者。可在网上搜索有关如何执行此操作的最新说明。

有关 Linux 上日志记录设施的介绍到此结束。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值