16. Linux 日志管理

操作系统内核和程序记录了发生的事件日志,这些日志用于审核系统并解决问题。日志以文本方式保存在/var/log目录中。可以使用普通文本实用程序(如less和tail)检查这些日志。

Linux 内置了基于Syslog协议的标准日志记录系统。许多程序使用此系统记录事件并将其组织到日志文件中。CentOS 7 中systemd-journald和rsyslog服务负责处理syslog消息。

  • systemd-journald 服务,是操作系统事件记录体系结构的核心,收集系统各方面事件消息,包括内核、引导过程早期阶段的输出、守护程序启动和运行时的输出、syslog事件,然后将它们重组为标准格式,并写入结构化的索引系统日志中。
  • rsyslog 服务,读取systemd-journald日志,然后记录到日志文件,或根据自己的配置将日志保存到不同的文件中,以及转发给其他程序。

rsyslog 日志配置

rsyslog 服务配置

配置文件位置
  • 主配置: /etc/rsyslog.conf。主配置文件中以下配置作用是引入从配置目录中配置文件。

    # Include all config files in /etc/rsyslog.d/
    include(file="/etc/rsyslog.d/*.conf" mode="optional")
    
  • 从配置:/etc/rsyslog.d/*.conf。

日志记录规则

每一条日志消息都可以通过消息类型facility和priority分类,参考rsyslog.conf(5)。

日志记录规则格式: facility+连接符号+priority 处理方式

facility(设备类型)

在这里插入图片描述

priority(优先级)

在这里插入图片描述

连接符

在这里插入图片描述

处理方式

  • 记录到文件
  • 发送到终端
  • 转发给其他服务器
配置文件内容

/etc/rsyslog.conf中部分内容如下:

### RULES ####
# Log all kernel messages to the console.
#kern.*                                                 /dev/console
*.info;mail.none;authpriv.none;cron.none                /var/log/messages
authpriv.*                                              /var/log/secure
mail.*                                                  -/var/log/maillog
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

在这里插入图片描述

注:主要查看前面两个日志。一定得记住

查看日志内容

[root@client ~ 13:50:14]# tail -f /var/log/messages
Sep 15 13:50:14 client systemd-logind: New session 3 of user root.
Sep 15 13:51:41 client systemd: Starting Cleanup of Temporary Directories...
Sep 15 13:51:41 client systemd: Started Cleanup of Temporary Directories.
Sep 15 14:01:01 client systemd: Started Session 4 of user root.
Sep 15 14:09:42 client auditd[731]: Audit daemon rotating log files
Sep 15 14:57:42 client auditd[731]: Audit daemon rotating log files
Sep 15 15:01:01 client systemd: Started Session 5 of user root.

日志内容说明:

  • Nov 10 10:23:34,代表日志产生时间。
  • centos7,产生日志的主机名。
  • systemd-logind,产生日志的进程。
  • 最后一个区域是日志内容,例如,“Removed session 15.”。
[root@client ~ 16:55:21]# tail -f /var/log/secure
Sep 15 13:36:09 client polkitd[754]: Acquired the name org.freedesktop.PolicyKit1 on the system bus
Sep 15 13:36:10 client sshd[1036]: Server listening on 0.0.0.0 port 22.
Sep 15 13:36:10 client sshd[1036]: Server listening on :: port 22.
Sep 15 13:36:10 client sshd[1046]: Accepted password for root from 10.1.8.1 port 52274 ssh2
....

自定义日志记录规则

[root@client ~ 17:00:32]# vim /etc/rsyslog.d/xs.conf
local5.* /var/log/xs.log
[root@client ~ 17:01:06]# systemctl restart rsyslog.service 
[root@client ~ 17:01:38]# ls /var/log/xs.log
ls: 无法访问/var/log/xs.log: 没有那个文件或目录

# 手动生成一个消息
[xs@client ~ 17:03:04]$ logger -p local5.info "test my log"
[xs@client ~ 17:05:41]$ su
[root@client xs 17:05:48]# cat /var/log/xs.log
Sep 15 17:03:56 client root: test my log

补充

  • 虽然系统提供了日志服务,但并不会记录所有内容。

  • 系统中的应用程序是否使用 rsyslog 服务记录日志,取决于应用程序设计。

    例如:

    • httpd 服务使用自己的日志记录。

    • sshd 服务使用 rsyslog 服务记录登录和退出日志。

      [root@server ~ 17:07:04]# grep AUTHPRIV /etc/ssh/sshd_config
      SyslogFacility AUTHPRIV
      
      [root@server ~ 17:07:26]# grep ^authpri /etc/rsyslog.conf 
      authpriv.*                                              /var/log/secure
      
      [root@server ~ 17:08:08]# tail -1 /var/log/secure
      Sep 15 16:52:00 server sshd[57297]: pam_unix(sshd:session): session opened for user root by (uid=0)
      

rsyslog 日志集中管理

多个客户端将日志发给服务端,由服务端统计记录。

服务端配置

# 启用 tcp 监听
[root@server ~ 17:08:38]# vim /etc/rsyslog.conf
# 取消如下两行记录注释
module(load="imtcp") # needs to be done just once
input(type="imtcp" port="514")

# 重启服务
[root@server ~ 17:10:15]# systemctl restart rsyslog.service 

# 关闭防火墙:停止并禁止开机自动启动
[root@server ~ 17:10:45]# systemctl disable firewalld.service --now

客户端配置

# 将本机所有日志通过tcp协议发送给远端服务器10.1.8.10
[root@client xs 17:12:07]# echo '*.* @@10.1.8.10' > /etc/rsyslog.d/remote.conf
[root@client xs 17:12:29]# systemctl restart rsyslog.service 

测试

# 服务端监控日志,客户端注销用户或者ssh登录
[root@server ~ 17:10:54]# tail -f /var/log/secure
Sep 15 15:57:59 server polkitd[754]: Unregistered Authentication Agent for unix-process:64279:851660 (system bus name :1.39, object path /org/freedesktop/PolicyKit1/AuthenticationAgent, locale zh_CN.UTF-8) (disconnected from bus)
Sep 15 15:58:13 server polkitd[754]: Registered Authentication Agent for unix-process:64840:853062 (system bus name :1.40 [/usr/bin/pkttyagent --notify-fd 5 --fallback], object path /org/freedesktop/PolicyKit1/AuthenticationAgent, locale zh_CN.UTF-8)
Sep 15 15:58:13 server polkitd[754]: Unregistered Authentication Agent for unix-process:64840:853062 (system bus name :1.40, object path /org/freedesktop/PolicyKit1/AuthenticationAgent, locale zh_CN.UTF-8) (disconnected from bus)
....

思考

如何将不同主机发来的日志分类到不同文件中?

systemd-journald 日志

systemd-journald 日志持久化保存

systemd-journald 配置文件 /etc/systemd/journald.conf

详情参考 journald.conf(5)

Storage参数,更改参数值后需要重启systemd-journald服务。

  • persistent:将日志存储在/var/log/journal目录中,这可在系统重启后持久保留。如果/var/log/journal目录不存在,systemd-journald服务会创建它。
  • volatile:将日志存储在易失性/run/log/journal目录中。因为/run文件系统是临时的,仅存在于运行时内存中,存储在其中的数据(包括系统日志)不会在系统启后持久保留。
  • auto:如果/var/log/journal目录存在,那么rsyslog会使用持久存储,否则使用易失性存储。如果未设置Storage参数,此为默认操作。
[root@client xs 17:12:48]# vim /etc/systemd/journald.conf
......
[Journal]
# Storage=auto
Storage=persistent
......
[root@centos7 ~ 17:12:48]# systemctl restart systemd-journald

systemd-journald 日志分析

[root@centos7 ~ 17:17:34]# ls /var/log/journal/
b8b0960cabe3452ca432f45acb1df028

# systemd-journald日志是以二进制方式存储,不能使用常规文本工具查看
# 查看所有日志条目,默认使用less查看文档
[root@server ~ 17:17:55]# journalctl
-- Logs begin at 一 2025-09-15 13:36:02 CST, end at 一 2025-09-15 17:17:04 CST. --
915 13:36:02 centos.xs systemd-journal[93]: Runtime journal is using 6.0M (max allowed 48
...
# 动态查看所有日志条目
[root@server ~ 17:18:58]# journalctl -f
-- Logs begin at 一 2025-09-15 13:36:02 CST. --
915 17:06:16 server.xs.cloud nm-dispatcher[90284]: req:1 'dhcp4-change' [ens37]: start running ordered scripts...
...
# 查看本次系统启动到现在所有日志条目
[root@server ~ 17:19:30]# journalctl -b 0
# 1 第1次启动的日志
# 2 第2次启动的日志
# N 第n次启动的日志

# 查看最近5条日志
[root@server ~ 17:20:01]# journalctl -n 5
-- Logs begin at 一 2025-09-15 13:36:02 CST, end at 一 2025-09-15 17:19:36 CST. --
915 17:19:36 server.xs.cloud dhclient[126775]: bound to 10.1.1.128 -- renewal in 731 seco
915 17:19:36 server.xs.cloud dbus[762]: [system] Successfully activated service 'org.free
9月 15 17:19:36 server.xs.cloud systemd[1]: Started Network Manager Script Dispatcher Servic
9月 15 17:19:36 server.xs.cloud nm-dispatcher[121160]: req:1 'dhcp4-change' [ens37]: new req
9月 15 17:19:36 server.xs.cloud nm-dispatcher[121160]: req:1 'dhcp4-change' [ens37]: start r
# 查看error级别日志
[root@server ~ 17:20:25]# journalctl -p err
[root@server ~ 17:20:27]# journalctl -p err|cat
-- Logs begin at 一 2025-09-15 13:36:02 CST, end at 一 2025-09-15 17:19:36 CST. --
915 13:36:02 centos.xs kernel: Detected CPU family 6 model 165 stepping 2
915 13:36:02 centos.xs kernel: Warning: Intel Processor - this hardware has not undergone
...

# 根据时间查看日志
[root@centos7 ~ 17:21:57]# journalctl --since today
[root@centos7 ~ 17:22:11]# journalctl --since "2019-02-10 20:30:00" --until "2019-02-13 12:00:00"
[root@centos7 ~ 17:22:25]# journalctl --since "-1 hour"

# 详细查看所有日志
[root@server ~ 17:22:30]# journalctl -o verbose 
-- Logs begin at 一 2025-09-15 13:36:02 CST, end at 一 2025-09-15 17:19:36 CST. --
一 2025-09-15 13:36:02.571653 CST [s=1e9494f3578b4cba9686ebce62a5691c;i=1;b=a9b694a4c8514537
    PRIORITY=6

# 查看特定unit日志
[root@server ~ 17:23:10]# journalctl -u sshd.service 
-- Logs begin at 一 2025-09-15 13:36:02 CST, end at 一 2025-09-15 17:19:36 CST. --
915 13:36:08 server.xs.cloud systemd[1]: Starting OpenSSH server daemon...
915 13:36:08 server.xs.cloud sshd[1044]: Server listening on 0.0.0.0 port 22.
....

故障模拟

故障1:配置文件丢失
[root@server ~ 17:24:04]# mv /etc/ssh/sshd_config .
[root@server ~ 17:24:17]# systemctl restart sshd
Job for sshd.service failed because the control process exited with error code. See "systemctl status sshd.service" and "journalctl -xe" for details.

处理过程:通过日志发现 /etc/ssh/sshd_config: No such file or directory,文件丢失。

# 重启服务时,动态监控日志
[root@server ~ 17:24:49]# journalctl -f
-- Logs begin at 一 2025-09-15 13:36:02 CST. --
....
915 17:24:27 server.xs.cloud polkitd[754]: Unregistered Authentication Agent for unix-process:1736:1370453 (system bus name :1.59, object path /org/freedesktop/PolicyKit1/AuthenticationAgent, locale zh_CN.UTF-8) (disconnected from bus)
915 17:25:09 server.xs.cloud systemd[1]: sshd.service holdoff time over, scheduling restart.
915 17:25:09 server.xs.cloud systemd[1]: Stopped OpenSSH server daemon.
915 17:25:09 server.xs.cloud systemd[1]: Starting OpenSSH server daemon...
915 17:25:09 server.xs.cloud sshd[3372]: /etc/ssh/sshd_config: No such file or directory
915 17:25:09 server.xs.cloud systemd[1]: sshd.service: main process exited, code=exited, status=1/FAILURE
915 17:25:09 server.xs.cloud systemd[1]: Failed to start OpenSSH server daemon.
915 17:25:09 server.xs.cloud systemd[1]: Unit sshd.service entered failed state.
915 17:25:09 server.xs.cloud systemd[1]: sshd.service failed.



# 移动回来,并重启服务
[root@server ~ 17:24:27]# mv sshd_config /etc/ssh/sshd_config
[root@server ~ 17:25:55]# systemctl restart sshd
[root@server ~ 17:26:02]# 
故障2:配置文件参数错误
[root@server ~ 17:26:02]# echo 'PermitRootLogin hahaha' >> /etc/ssh/sshd_config
[root@server ~ 17:26:31]# systemctl restart sshd
Job for sshd.service failed because the control process exited with error code. See "systemctl status sshd.service" and "journalctl -xe" for details.

处理过程:通过日志发现/etc/ssh/sshd_config line 141: unsupported option "hahaha".

# 重启服务时,动态监控日志
[[root@server ~ 17:26:23]# journalctl -f
-- Logs begin at 一 2025-09-15 13:36:02 CST. --
915 17:27:19 server.xs.cloud systemd[1]: sshd.service holdoff time over, scheduling restart.
915 17:27:19 server.xs.cloud systemd[1]: Stopped OpenSSH server daemon.
915 17:27:19 server.xs.cloud systemd[1]: Starting OpenSSH server daemon...
915 17:27:19 server.xs.cloud sshd[8397]: /etc/ssh/sshd_config line 140: unsupported option "hahaha".

915 17:27:19 server.xs.cloud systemd[1]: sshd.service: main process exited, code=exited, status=255/n/a
915 17:27:19 server.xs.cloud systemd[1]: Failed to start OpenSSH server daemon.
915 17:27:19 server.xs.cloud systemd[1]: Unit sshd.service entered failed state.
915 17:27:19 server.xs.cloud systemd[1]: sshd.service failed.


# 清理对应无效记录,并重启服务
[root@server ~ 17:26:37]# sed -i '/hahaha/d' /etc/ssh/sshd_config
[root@server ~ 17:28:14]# systemctl restart sshd
[root@server ~ 17:28:27]# 
故障3:配置文件参数错误
[root@centos7 ~]# yum install -y httpd
[root@server ~ 17:29:19]# sed -i 's/Listen 80/Listen 80000/g' /etc/httpd/conf/httpd.conf
[root@server ~ 17:29:32]# systemctl restart httpd
Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details.

处理过程:通过日志发现 AH00526: Syntax error on line 42 of /etc/httpd/conf/httpd.conf

# 重启服务时,动态监控日志
[root@server ~ 17:30:17]# journalctl -f
-- Logs begin at 一 2025-09-15 13:36:02 CST. --
915 17:29:46 server.xs.cloud systemd[1]: Stopping The Apache HTTP Server...
915 17:29:47 server.xs.cloud systemd[1]: Stopped The Apache HTTP Server.
915 17:29:47 server.xs.cloud systemd[1]: Starting The Apache HTTP Server...
915 17:29:47 server.xs.cloud httpd[14152]: AH00526: Syntax error on line 42 of /etc/httpd/conf/httpd.conf:
915 17:29:47 server.xs.cloud httpd[14152]: Invalid address or port
915 17:29:47 server.xs.cloud systemd[1]: httpd.service: main process exited, code=exited, status=1/FAILURE
915 17:29:47 server.xs.cloud systemd[1]: Failed to start The Apache HTTP Server.
915 17:29:47 server.xs.cloud systemd[1]: Unit httpd.service entered failed state.
915 17:29:47 server.xs.cloud systemd[1]: httpd.service failed.
915 17:29:47 server.xs.cloud polkitd[754]: Unregistered Authentication Agent for unix-process:14115:1402374 (system bus name :1.63, object path /org/freedesktop/PolicyKit1/AuthenticationAgent, locale zh_CN.UTF-8) (disconnected from bus)



# 修改回来,并重启服务
[root@server ~ 17:29:47]# sed -i 's/Listen 80000/Listen 80/g' /etc/httpd/conf/httpd.conf
[root@server ~ 17:30:57]# systemctl restart httpd
[root@server ~ 17:30:59]# 

17. Linux 时间管理

系统时间设置

时间管理主要是通过IP地址来进行锚定的,通过ip地址查询具体地址来进行查询时间。

date 命令

[root@server ~ 17:30:59]# LANG=en_US.utf8 date
Mon Sep 15 17:31:55 CST 2025

# 设置为特定时间,字符串以英文格式表达
[root@server ~ 17:31:55]# date -s '2022年 11月 11日 星期四 11:30:10 CST'
date: 无效的日期"2022年 11月 11日 星期四 11:30:10 CST"

[root@server ~ 17:32:07]# date -s 'Thu Nov 11 11:30:59 CST 2022'
20221111日 星期五 11:30:59 CST

hwclock 命令

# 读取硬件时钟
[root@server ~ 11:30:59]# hwclock -r
2025年09月15日 星期一 17时33分18秒  -0.365057 秒

# 将硬件时钟时间设置与系统时间一致
[root@server ~ 11:31:38]# hwclock -w

# 将系统时间设置与硬件时钟时间一致
[root@server ~ 11:32:12]# hwclock -s

timedatectl 命令

[root@server ~ 11:32:19]# timedatectl 
      Local time: 五 2022-11-11 11:33:36 CST
  Universal time: 五 2022-11-11 03:33:36 UTC
        RTC time: 五 2022-11-11 03:33:37
       Time zone: Asia/Shanghai (CST, +0800)
     NTP enabled: yes
NTP synchronized: no
 RTC in local TZ: no
      DST active: n/a

# RTC real time clock,也就是硬件时钟时间。
# NTP enabled: yes,代表对时服务chronyd应开机自启。

# 关闭自动对时
[root@server ~ 11:33:37]# timedatectl set-ntp no
[root@server ~ 11:34:01]# timedatectl 
      Local time: 五 2022-11-11 11:34:04 CST
  Universal time: 五 2022-11-11 03:34:04 UTC
        RTC time: 五 2022-11-11 03:34:04
       Time zone: Asia/Shanghai (CST, +0800)
     NTP enabled: no
NTP synchronized: no
 RTC in local TZ: no
      DST active: n/a


[root@server ~ 11:34:04]# LANG=en_US.utf8
[root@server ~ 11:34:33]# timedatectl set-time '2022-11-10 11:42:54'

# 如果自动对时未关闭,显示如下
[root@centos7 ~ 11:34:39]# timedatectl set-time '2022-11-10 11:42:54'
Failed to set time: Automatic time synchronization is enabled

# 设置时区
[root@centos7 ~ 11:34:56]# timedatectl set-timezone Asia/Shanghai

tzselect 命令

查询时区名称。

[root@server ~ 11:42:54]# tzselect
Please identify a location so that time zone rules can be set correctly.
Please select a continent or ocean.
 1) Africa
 2) Americas
 3) Antarctica
 4) Arctic Ocean
 5) Asia
 6) Atlantic Ocean
 7) Australia
 8) Europe
 9) Indian Ocean
10) Pacific Ocean
11) none - I want to specify the time zone using the Posix TZ format.
#?  5
Please select a country.
 1) Afghanistan           18) Israel                35) Palestine
 2) Armenia               19) Japan                 36) Philippines
 3) Azerbaijan            20) Jordan                37) Qatar
 4) Bahrain               21) Kazakhstan            38) Russia
 5) Bangladesh            22) Korea (North)         39) Saudi Arabia
 6) Bhutan                23) Korea (South)         40) Singapore
 7) Brunei                24) Kuwait                41) Sri Lanka
 8) Cambodia              25) Kyrgyzstan            42) Syria
 9) China                 26) Laos                  43) Taiwan
10) Cyprus                27) Lebanon               44) Tajikistan
11) East Timor            28) Macau                 45) Thailand
12) Georgia               29) Malaysia              46) Turkmenistan
13) Hong Kong             30) Mongolia              47) United Arab Emirates
14) India                 31) Myanmar (Burma)       48) Uzbekistan
15) Indonesia             32) Nepal                 49) Vietnam
16) Iran                  33) Oman                  50) Yemen
17) Iraq                  34) Pakistan
#? 9
Please select one of the following time zone regions.
1) Beijing Time
2) Xinjiang Time
#? 1

The following information has been given:

        China
        Beijing Time

Therefore TZ='Asia/Shanghai' will be used.
Local time is now:      Thu Nov 10 11:45:49 CST 2022.
Universal Time is now:  Thu Nov 10 03:45:49 UTC 2022.
Is the above information OK?
1) Yes
2) No
#? 1

You can make this change permanent for yourself by appending the line
        TZ='Asia/Shanghai'; export TZ
to the file '.profile' in your home directory; then log out and log in again.

Here is that TZ value again, this time on standard output so that you
can use the /usr/bin/tzselect command in shell scripts:
Asia/Shanghai

windows 自动对时

在这里插入图片描述

自动对时-chronyd 服务

# 修改对时服务器
[root@server ~ 11:45:53]# vim /etc/chrony.conf
# 与时间池对时(查找并修改)
# 时间池是包含多个时间服务器的服务器组
pool 2.rocky.pool.ntp.org iburst

# 与单个服务器 ntp.aliyun.com 对时
server ntp.aliyun.com iburst

# 启用并启动chronyd服务
[root@server ~ 11:47:01]# systemctl enable chronyd --now

# 如果之前已经启动,需要重启
[root@server ~ 11:47:51]# systemctl restart chronyd


# 验证对时情况
[root@server ~ 11:48:25]# chronyc sources -v
  .-- Source mode  '^' = server, '=' = peer, '#' = local clock.
 / .- Source state '*' = current best, '+' = combined, '-' = not combined,
| /             'x' = may be in error, '~' = too variable, '?' = unusable.
||                                                 .- xxxx [ yyyy ] +/- zzzz
||      Reachability register (octal) -.           |  xxxx = adjusted offset,
||      Log2(Polling interval) --.      |          |  yyyy = measured offset,
||                                \     |          |  zzzz = estimated error.
||                                 |    |           \
MS Name/IP address         Stratum Poll Reach LastRx Last sample               
===============================================================================
^* 203.107.6.88                2   6    77     9  -1840us[-4378us] +/-   23ms

部署时间服务器

chrony既可以作为客户端,也可以作为服务端(为客户端提供对时服务)。

服务端

[root@server ~ 11:48:51]# vim /etc/chrony.conf
# 最后添加两条记录

# 配置监听地址
bindaddress 10.1.8.10

# 配置允许哪些网段主机同步
allow 10.1.8.0/24

[root@server ~ 11:49:43]]# systemctl restart chronyd

# 停止防火墙服务
[root@server ~ 11:50:50]# systemctl stop firewalld.service

客户端

# 修改对时服务器
[root@client xs 17:17:46]# vim /etc/chrony.conf
# 与单个服务器 10.1.8.10 对时
server 10.1.8.10 iburst

[root@client ~ 17:47:55]# systemctl restart chronyd
[root@client ~ 17:48:11]# chronyc sources -v
210 Number of sources = 1

  .-- Source mode  '^' = server, '=' = peer, '#' = local clock.
 / .- Source state '*' = current synced, '+' = combined , '-' = not combined,
| /   '?' = unreachable, 'x' = time may be in error, '~' = time too variable.
||                                                 .- xxxx [ yyyy ] +/- zzzz
||      Reachability register (octal) -.           |  xxxx = adjusted offset,
||      Log2(Polling interval) --.      |          |  yyyy = measured offset,
||                                \     |          |  zzzz = estimated error.
||                                 |    |           \
MS Name/IP address         Stratum Poll Reach LastRx Last sample               
===============================================================================
^* server.laoma.cloud            3   6     7     1    -10us[  +43ms] +/-   76ms
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐