【Linux命令】《鸟哥Linux基础》第十八章 认识与分析日志文件

第十八章 认识与分析日志文件

日志文件可以记录系统在什么时间、哪个主机、哪个服务、出现了什么信息等内容,这些信息也包括用户识别数据、系统故障排除须知等信息。

18.1 什么是日志文件

仔细而确实地分析以及备份系统的日志文件是一个系统管理员应该要进行的任务之一。

日志文件就是记录系统活动信息的几个文件:何时、何地(来源IP)、何人(什么服务名)、做了什么操作(信息登录)。或者说,就是记录系统在什么时候由哪个进程做了什么样的操作时,发生了何种的事件。

18.1.1 CentOS日志文件简要说明

权限通常是设置为仅有root能够读取。

常见的日志文件简介
/var/log/boot.log保存本次开机启动信息
/var/log/cron计划任务
/var/log/dmesg记录系统在开机的时候内核检测过程所产生的各项信息
/var/log/lastlog记录系统上所有的账号最近一次登录系统时的相关信息
/var/log/maillog或/var/log/mail/*记录邮件往来信息,主要记录postfix(SMTP协议提供者)、dovecot(POP3协议提供者)所产生的信息
/var/log/messages重要!!!系统发生的错误信息
/var/log/secure牵涉到需要输入账号密码的软件,登录时都会被记录在此
/var/log/wtmp、/var/log/faillog记录正确登录系统者的账户信息(wtmp)、错误登录时所使用的账户信息(faillog)
/var/log/httpd/*、/var/log/samba/下的所有不同的网络服务会使用他们自己的日志文件记录他们自己产生的信息

针对日志文件所需的功能,需要的服务与程序有:

服务与程序功能
systemd-journald.service最主要的信息记录者,有systemd提供
rsyslog.service主要收集登录系统与网络等服务的信息
logrotate主要在进行日志文件的轮询功能

18.2 rsyslog.service:记录日志文件的服务

[root@study ~]$ ps aux | grep rsyslog				查看Linux是否启动了rsyslog
root       1221  0.0  0.4 214452  4172 ?        Ssl  11:16   0:00 /usr/sbin/rsyslogd -n
root       2883  0.0  0.0 112732   976 pts/0    R+   11:21   0:00 grep --color=auto rsyslog



[root@study ~]$ systemctl status rsyslog.service	确认下:该服务启动了,而且开机自启动
● rsyslog.service - System Logging Service
   Loaded: loaded (/usr/lib/systemd/system/rsyslog.service; enabled; vendor preset: enabled)
   Active: active (running) since 一 2020-06-15 11:16:30 CST; 7min ago
     Docs: man:rsyslogd(8)
           http://www.rsyslog.com/doc/
 Main PID: 1221 (rsyslogd)
    Tasks: 3
   CGroup: /system.slice/rsyslog.service
           └─1221 /usr/sbin/rsyslogd -n

6月 15 11:16:30 study.centos.vbird systemd[1]: Starting System Logging Service...
6月 15 11:16:30 study.centos.vbird rsyslogd[1221]:  [origin software="rsyslogd" swVersion="8.24.0-38.el7" x-pid="1221" x-info="htt... start
6月 15 11:16:30 study.centos.vbird systemd[1]: Started System Logging Service.
Hint: Some lines were ellipsized, use -l to show in full.

18.2.1 rsyslog.service的配置文件:/etc/rsyslog.conf

服务含义
syslog这个是Linux内核提供的日志文件设计指引,所有要求都写到一个名为syslog.h的头文件中。如果想要开发与日志文件有关的软件,那你就得要依据这个syslog函数的要求去设计才行
rsyslogd为了要完成实际上进行信息分类所开发的一个软件,所以这就是最基本的daemon程序
rsyslog.service为了加入systemd的控制,因此rsyslogd的开发者设计的启动服务脚本设置
cat /etc/rsyslog.conf
输出:
# rsyslog configuration file

# For more information see /usr/share/doc/rsyslog-*/rsyslog_conf.html
# If you experience problems, see http://www.rsyslog.com/doc/troubleshoot.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

$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
自行增加日志文件功能:

想要所有的信息额外写入到/var/log/admin.log这个文件时:

[root@study ~]$ vim /etc/rsyslog.conf					修改配置文件
[root@study ~]$ cat /etc/rsyslog.conf | head -n 3		查看配置文件的前三行
# Added by dingjing 2020-06-15							要记得加备注
*.info /var/log/admin.log								这里是真正起作用的


[root@study ~]$ systemctl restart rsyslog.service		重启rsyslogd服务
[root@study ~]$ ll /var/log/admin.log					查看是否建立了日志文件
-rw-------. 1 root root 816 6月  15 15:05 /var/log/admin.log	的确建立了

这样,所有的信息都会写入/var/log/admin.log文件中一份了。

18.2.2 日志文件的安全性设置

日志文件应该被设置为只能增加数据,不能删除数据。

日志文件只要被编辑过就不能继续记录了。所以用vim编辑日志文件后,千万不要w,直接q即可。如果用了wq,那么重启rsyslog.service让它继续提供服务。

第六章学到的lsattrcharttr可以设置隐藏属性。

[root@study ~]$ chattr +a /var/log/admin.log		只能追加内容,此时连root也不能修改它
[root@study ~]$ lsattr /var/log/admin.log			查看一下属性
-----a---------- /var/log/admin.log



[root@study ~]$ chattr -a /var/log/admin.log		通过root取消a这个参数后,才能被删除或移动
[root@study ~]$ lsattr /var/log/admin.log
---------------- /var/log/admin.log	

如果不取消掉+a属性,那后面使用logrotate的时候难以重命名日志文件。

18.2.3 日志文件服务器的设置

Linux主机会启动514端口监听。

Server端:

[root@study ~]$ vim /etc/rsyslog.conf
找到下面的行:
# Provides UDP syslog reception
#$ModLoad imudp
#$UDPServerRun 514
# Provides TCP syslog reception
$ModLoad imtcp						将这两行取消注释即可
$InputTCPServerRun 514				将这两行取消注释即可


[root@study ~]$ systemctl restart rsyslog.service		重启服务
[root@study ~]$ netstat -ltnp | grep syslog				查看端口
tcp        0      0 0.0.0.0:514             0.0.0.0:*               LISTEN      2942/rsyslogd       
tcp6       0      0 :::514                  :::*                    LISTEN      2942/rsyslogd 

此时,Linux主机已经可以接收来自其他主机的登录信息了。

Client端:

[root@study ~]$ vim /etc/rsyslog.conf					将数据发送到服务端
*.*		@@192.168.1.100		因为是TCP所以用这个(假设服务器主机的IP地址是192.168.1.100)
#*.*	@@192.168.1.100		如果是UDP则是这个

[root@study ~]$ systemctl restart rsyslog.service		重启服务

18.3 日志文件的轮询(logrotate)

这个logrotate程序是在规定时间到了之后才进行日志文件的轮询,所以该程序是挂在cron下面进行的。

logrotate的主要功能是:将现有的日志文件重新命名以做备份,然后重新建立一个空文件来记录信息。

18.3.1 logrotate的配置文件

配置文件需要设置:在什么状态下才将日志文件进行轮询。

配置文件位置:

  • /etc/logrotate.conf 主要的参数文件
  • /etc/logrotate.d 是个目录,这里面的所有文件都会被主动读入上面的配置文件中使用
[root@study ~]$ vim /etc/logrotate.conf
#see "man logrotate" for details
# rotate log files weekly
weekly

# keep 4 weeks worth of backlogs
rotate 4

# create new (empty) log files after rotating old ones
create

# use date as a suffix of the rotated file
dateext

# uncomment this if you want your log files compressed
#compress

# RPM packages drop log rotation information into this directory
include /etc/logrotate.d

# no packages own wtmp and btmp -- we'll rotate them here
/var/log/wtmp {
    monthly
    create 0664 root utmp
        minsize 1M
    rotate 1
}

/var/log/btmp {
    missingok
    monthly
    create 0600 root utmp
    rotate 1
}

# system-specific logs may be also be configured here.

/etc/logrotate.d/syslog这个轮询rsyslog.service服务的文件为例,看如何设置它的轮循:

vim /etc/logrotate.d/syslog
输出:
/var/log/cron
/var/log/maillog
/var/log/messages
/var/log/secure
/var/log/spooler
{
    missingok
    sharedscripts
    postrotate
        /bin/kill -HUP `cat /var/run/syslogd.pid 2> /dev/null` 2> /dev/null || true
    endscript
}

如果刚才加入了+a这个特殊属性,那么可以这么修改:

vim /etc/logrotate.d/syslog
输出:
/var/log/cron
/var/log/maillog
/var/log/messages
/var/log/secure
/var/log/spooler
{
    prerotate		
    	/usr/bin/chattr -a /var/log/messages		改名之前先把a属性去掉
    endscript
    sharedscripts
    postrotate		由于创建了一个新的文件用于保存日志,因此必须得用下面这句话重新读入配置文件rsyslog.conf更新rsyslogd服务
        /bin/kill -HUP `cat /var/run/syslogd.pid 2> /dev/null` 2> /dev/null || true
        /usr/bin/chattr +a /var/log/message			改名之后再把a属性加上
    endscript
}

18.3.2 实际测试logrotate的操作

命令1,及其显示信息:

[root@study ~]$ logrotate -v /etc/logrotate.conf		
reading config file /etc/logrotate.conf
including /etc/logrotate.d
reading config file bootlog
reading config file chrony
reading config file cups
reading config file iscsiuiolog
reading config file libvirtd
reading config file libvirtd.qemu
reading config file numad
reading config file ppp
reading config file psacct
reading config file samba
olddir is now /var/log/samba/old
reading config file syslog
reading config file wpa_supplicant
reading config file yum
Allocating hash table for state file, size 15360 B

Handling 15 logs

rotating pattern: /var/log/boot.log
 after 1 days (7 rotations)
empty log files are not rotated, old logs are removed
considering log /var/log/boot.log
  log does not need rotating (log has been rotated at 2020-6-15 12:50, that is not day ago yet)

rotating pattern: /var/log/chrony/*.log  weekly (4 rotations)
empty log files are rotated, old logs are removed
considering log /var/log/chrony/*.log
  log /var/log/chrony/*.log does not exist -- skipping
not running postrotate script, since no logs were rotated

rotating pattern: /var/log/cups/*_log  weekly (4 rotations)
empty log files are not rotated, old logs are removed
considering log /var/log/cups/access_log
  log does not need rotating (log has been rotated at 2020-6-14 15:36, that is not week ago yet)
considering log /var/log/cups/error_log
  log does not need rotating (log is empty)considering log /var/log/cups/page_log
  log does not need rotating (log is empty)
rotating pattern: /var/log/iscsiuio.log  weekly (4 rotations)
empty log files are not rotated, old logs are removed
considering log /var/log/iscsiuio.log
  log /var/log/iscsiuio.log does not exist -- skipping
not running postrotate script, since no logs were rotated

rotating pattern: /var/log/libvirt/libvirtd.log  weekly (4 rotations)
empty log files are rotated, only log files >= 102400 bytes are rotated, old logs are removed
considering log /var/log/libvirt/libvirtd.log
  log /var/log/libvirt/libvirtd.log does not exist -- skipping

rotating pattern: /var/log/libvirt/qemu/*.log  weekly (4 rotations)
empty log files are rotated, old logs are removed
considering log /var/log/libvirt/qemu/*.log
  log /var/log/libvirt/qemu/*.log does not exist -- skipping

rotating pattern: /var/log/numad.log  1048576 bytes (5 rotations)
empty log files are rotated, old logs are removed
considering log /var/log/numad.log
  log /var/log/numad.log does not exist -- skipping

rotating pattern: /var/log/ppp/connect-errors  after 1 days (5 rotations)
empty log files are not rotated, old logs are removed
considering log /var/log/ppp/connect-errors
  log /var/log/ppp/connect-errors does not exist -- skipping

rotating pattern: /var/account/pacct  after 1 days (31 rotations)
empty log files are not rotated, old logs are removed
considering log /var/account/pacct
  log does not need rotating (log is empty)
rotating pattern: /var/log/samba/*  weekly (4 rotations)
olddir is /var/log/samba/old, empty log files are not rotated, old logs are removed
No logs found. Rotation not needed.

rotating pattern: /var/log/cron
/var/log/maillog
/var/log/messages
/var/log/secure
/var/log/spooler
 weekly (4 rotations)
empty log files are rotated, old logs are removed
considering log /var/log/cron
  log does not need rotating (log has been rotated at 2020-6-14 15:36, that is not week ago yet)
considering log /var/log/maillog
  log does not need rotating (log has been rotated at 2020-6-14 15:36, that is not week ago yet)
considering log /var/log/messages
  log does not need rotating (log has been rotated at 2020-6-14 15:36, that is not week ago yet)
considering log /var/log/secure
  log does not need rotating (log has been rotated at 2020-6-14 15:36, that is not week ago yet)
considering log /var/log/spooler
  log does not need rotating (log has been rotated at 2020-6-14 15:36, that is not week ago yet)
not running postrotate script, since no logs were rotated

rotating pattern: /var/log/wpa_supplicant.log  30720 bytes (4 rotations)
empty log files are not rotated, old logs are removed
considering log /var/log/wpa_supplicant.log
  log does not need rotating (log size is below the 'size' threshold)

rotating pattern: /var/log/yum.log  yearly (4 rotations)
empty log files are not rotated, log files >= 30720 are rotated earlier, old logs are removed
considering log /var/log/yum.log
  log does not need rotating (log has been rotated at 2020-4-30 8:0, that is not year ago yet)

rotating pattern: /var/log/wtmp  monthly (1 rotations)
empty log files are rotated, only log files >= 1048576 bytes are rotated, old logs are removed
considering log /var/log/wtmp
  log does not need rotating ('misinze' directive is used and the log size is smaller than the minsize value
rotating pattern: /var/log/btmp  monthly (1 rotations)
empty log files are rotated, old logs are removed
considering log /var/log/btmp
  log does not need rotating (log has been rotated at 2020-6-6 10:45, that is not month ago yet)
set default create context

命令2,及其显示信息:

[root@study ~]$ logrotate -vf /etc/logrotate.conf		强制写入
reading config file /etc/logrotate.conf
including /etc/logrotate.d
reading config file bootlog
reading config file chrony
reading config file cups
reading config file iscsiuiolog
reading config file libvirtd
reading config file libvirtd.qemu
reading config file numad
reading config file ppp
reading config file psacct
reading config file samba
olddir is now /var/log/samba/old
reading config file syslog
reading config file wpa_supplicant
reading config file yum
Allocating hash table for state file, size 15360 B

Handling 15 logs

rotating pattern: /var/log/boot.log
 forced from command line (7 rotations)
empty log files are not rotated, old logs are removed
considering log /var/log/boot.log
  log needs rotating
rotating log /var/log/boot.log, log->rotateCount is 7
dateext suffix '-20200615'
glob pattern '-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'
destination /var/log/boot.log-20200615 already exists, skipping rotation

rotating pattern: /var/log/chrony/*.log  forced from command line (4 rotations)
empty log files are rotated, old logs are removed
considering log /var/log/chrony/*.log
  log /var/log/chrony/*.log does not exist -- skipping
not running postrotate script, since no logs were rotated

rotating pattern: /var/log/cups/*_log  forced from command line (4 rotations)
empty log files are not rotated, old logs are removed
considering log /var/log/cups/access_log
  log does not need rotating (log is empty)considering log /var/log/cups/error_log
  log does not need rotating (log is empty)considering log /var/log/cups/page_log
  log does not need rotating (log is empty)
rotating pattern: /var/log/iscsiuio.log  forced from command line (4 rotations)
empty log files are not rotated, old logs are removed
considering log /var/log/iscsiuio.log
  log /var/log/iscsiuio.log does not exist -- skipping
not running postrotate script, since no logs were rotated

rotating pattern: /var/log/libvirt/libvirtd.log  forced from command line (4 rotations)
empty log files are rotated, only log files >= 102400 bytes are rotated, old logs are removed
considering log /var/log/libvirt/libvirtd.log
  log /var/log/libvirt/libvirtd.log does not exist -- skipping

rotating pattern: /var/log/libvirt/qemu/*.log  forced from command line (4 rotations)
empty log files are rotated, old logs are removed
considering log /var/log/libvirt/qemu/*.log
  log /var/log/libvirt/qemu/*.log does not exist -- skipping

rotating pattern: /var/log/numad.log  forced from command line (5 rotations)
empty log files are rotated, old logs are removed
considering log /var/log/numad.log
  log /var/log/numad.log does not exist -- skipping

rotating pattern: /var/log/ppp/connect-errors  forced from command line (5 rotations)
empty log files are not rotated, old logs are removed
considering log /var/log/ppp/connect-errors
  log /var/log/ppp/connect-errors does not exist -- skipping

rotating pattern: /var/account/pacct  forced from command line (31 rotations)
empty log files are not rotated, old logs are removed
considering log /var/account/pacct
  log does not need rotating (log is empty)
rotating pattern: /var/log/samba/*  forced from command line (4 rotations)
olddir is /var/log/samba/old, empty log files are not rotated, old logs are removed
No logs found. Rotation not needed.

rotating pattern: /var/log/cron
/var/log/maillog
/var/log/messages
/var/log/secure
/var/log/spooler
 forced from command line (4 rotations)
empty log files are rotated, old logs are removed
considering log /var/log/cron
  log needs rotating
considering log /var/log/maillog
  log needs rotating
considering log /var/log/messages
  log needs rotating
considering log /var/log/secure
  log needs rotating
considering log /var/log/spooler
  log needs rotating
rotating log /var/log/cron, log->rotateCount is 4
dateext suffix '-20200615'
glob pattern '-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'
rotating log /var/log/maillog, log->rotateCount is 4
dateext suffix '-20200615'
glob pattern '-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'
rotating log /var/log/messages, log->rotateCount is 4
dateext suffix '-20200615'
glob pattern '-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'
rotating log /var/log/secure, log->rotateCount is 4
dateext suffix '-20200615'
glob pattern '-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'
rotating log /var/log/spooler, log->rotateCount is 4
dateext suffix '-20200615'
glob pattern '-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'
fscreate context set to system_u:object_r:cron_log_t:s0
renaming /var/log/cron to /var/log/cron-20200615
creating new /var/log/cron mode = 0600 uid = 0 gid = 0
fscreate context set to system_u:object_r:var_log_t:s0
renaming /var/log/maillog to /var/log/maillog-20200615
creating new /var/log/maillog mode = 0600 uid = 0 gid = 0
fscreate context set to system_u:object_r:var_log_t:s0
renaming /var/log/messages to /var/log/messages-20200615
creating new /var/log/messages mode = 0600 uid = 0 gid = 0
fscreate context set to system_u:object_r:var_log_t:s0
renaming /var/log/secure to /var/log/secure-20200615
creating new /var/log/secure mode = 0600 uid = 0 gid = 0
fscreate context set to system_u:object_r:var_log_t:s0
renaming /var/log/spooler to /var/log/spooler-20200615
creating new /var/log/spooler mode = 0600 uid = 0 gid = 0
running postrotate script
removing old log /var/log/cron-20200526
removing old log /var/log/maillog-20200526
removing old log /var/log/messages-20200526
removing old log /var/log/secure-20200526
removing old log /var/log/spooler-20200526

rotating pattern: /var/log/wpa_supplicant.log  forced from command line (4 rotations)
empty log files are not rotated, old logs are removed
considering log /var/log/wpa_supplicant.log
  log needs rotating
rotating log /var/log/wpa_supplicant.log, log->rotateCount is 4
dateext suffix '-20200615'
glob pattern '-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'
glob finding old rotated logs failed
fscreate context set to system_u:object_r:NetworkManager_log_t:s0
renaming /var/log/wpa_supplicant.log to /var/log/wpa_supplicant.log-20200615
creating new /var/log/wpa_supplicant.log mode = 0600 uid = 0 gid = 0

rotating pattern: /var/log/yum.log  forced from command line (4 rotations)
empty log files are not rotated, log files >= 30720 are rotated earlier, old logs are removed
considering log /var/log/yum.log
  log does not need rotating (log is empty)
rotating pattern: /var/log/wtmp  forced from command line (1 rotations)
empty log files are rotated, only log files >= 1048576 bytes are rotated, old logs are removed
considering log /var/log/wtmp
  log needs rotating
rotating log /var/log/wtmp, log->rotateCount is 1
dateext suffix '-20200615'
glob pattern '-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'
glob finding old rotated logs failed
fscreate context set to system_u:object_r:wtmp_t:s0
renaming /var/log/wtmp to /var/log/wtmp-20200615
creating new /var/log/wtmp mode = 0664 uid = 0 gid = 22

rotating pattern: /var/log/btmp  forced from command line (1 rotations)
empty log files are rotated, old logs are removed
considering log /var/log/btmp
  log needs rotating
rotating log /var/log/btmp, log->rotateCount is 1
dateext suffix '-20200615'
glob pattern '-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'
fscreate context set to system_u:object_r:faillog_t:s0
renaming /var/log/btmp to /var/log/btmp-20200615
creating new /var/log/btmp mode = 0600 uid = 0 gid = 22
removing old log /var/log/btmp-20200606
set default create context

查询文件属性和权限:

[root@study ~]$ ll /var/log/messages*;lsattr /var/log/messages
-rw-------. 1 root root     151 6月  15 17:06 /var/log/messages
-rw-------. 1 root root  641458 5月  31 15:06 /var/log/messages-20200531
-rw-------. 1 root root  874596 6月   7 09:40 /var/log/messages-20200607
-rw-------. 1 root root 2338686 6月  14 15:36 /var/log/messages-20200614
-rw-------. 1 root root  487242 6月  15 17:01 /var/log/messages-20200615
---------------- /var/log/messages

18.3.3 自定义日志文件的轮询功能

1、给log文件增加+a这个属性:

[root@study ~]$ chattr +a /var/log/admin.log


[root@study ~]$ lsattr /var/log/admin.log
-----a---------- /var/log/admin.log


[root@study ~]$ mv /var/log/admin.log /var/log/admin.log.1	 确认一下确实不能乱修改文件名
mv: 无法将"/var/log/admin.log" 移动至"/var/log/admin.log.1": 不允许的操作

2、开始建立logrotate的配置文件,增加一个文件到/etc/logrotate.d/目录中就可以:

[root@study ~]$ vim /etc/logrotate.d/admin
[root@study ~]$ cat /etc/logrotate.d/admin		
# This config is from dj 2020-06-15
/var/log/admin.log{
	monthly			每月一次
	size=10M		文件容量超过10M,立刻开始轮循
	rotate 5		保留5个
	compress		进行压缩工作
	sharedscripts	
	prerotate
		/usr/bin/chattr -a /var/log/admin.log
	endscript
	sharedscripts
	postrotate
		/bin/kill -HUP `cat /var/run/syslogd.pid 2> /dev/null` 2> /dev/null || true
		/usr/bin/chattr +a /var/log/admin.log
	endscript
}

3、测试一下轮循功能:(因为还不足一个月,文件也没有大于10M,所以无需轮循)

[root@study ~]$ logrotate -v /etc/logrotate.conf		
reading config file /etc/logrotate.conf
including /etc/logrotate.d
reading config file admin
reading config file bootlog
reading config file chrony
...

4、测试一下强制logrotate与相关功能的信息显示:

[root@study ~]$ logrotate -vf /etc/logrotate.d/admin	
reading config file /etc/logrotate.d/admin
Allocating hash table for state file, size 15360 B
Handling 1 logs
...

通过以上4步,我们可以建立起属于自己的logrotate配置文件。

18.4 systemd-journald.service简介

18.4.1 使用journalctl查看登录信息

就是使用journalctl调出日志信息给我们看:

journalctl [-nrpf] [--since TIME] [--until TIME] _optional
			默认会显示全部的log内容,从旧的输出到最新的信息:
				-n	显示最近几行的意思,找最新的信息
				-r	反向输出,从最新的输出到最近的
				-p	显示后面所接的信息重要性排序
				-f	类似tail -f的功能,持续显示journal日志的内容(即时检测时相当有帮助)
				--since --unitl	设置开始和结束的时间,让在该期间的数据输出而已
				_SYSTEMD_UNIT=unit.service	只输出unit.service的信息而已
				_COMM=bash		只输出与此bash有关的信息
				_PID=pid		只输出与此PID有关的信息
				_UID=uid		只输出与此UID有关的信息
				SYSLOG_FACILITY	使用syslog.h规范的服务相对序号来调用出正确的数据	
journalctl						显示目前系统中所有的journal日志数据
journalctl --since "2020-06-15 00:00:00" --until "2020-06-16 00:00:00"	显示6月15一整天的信息
journalctl --since today 		仅当天的日志数据内容
journalctl --since yesterday --until today	从昨天到今天的日志数据




[root@study ~]$ journalctl _SYSTEMD_UNIT=crond.service -n 10	只找出crond.service的数据,显示最近的10条信息
-- Logs begin at 一 2020-06-15 15:16:04 CST, end at 一 2020-06-15 19:11:01 CST. --
6月 15 15:16:39 study.centos.vbird crond[1182]: (CRON) INFO (RANDOM_DELAY will be scaled with factor 16% if used.)
6月 15 15:16:41 study.centos.vbird crond[1182]: (CRON) INFO (running with inotify support)




[root@study ~]$ journalctl _COMM=su _COMM=login -n 10			找出su和login产生的日志,只看10条最新数据
-- Logs begin at 一 2020-06-15 15:16:04 CST, end at 一 2020-06-15 19:20:02 CST. --
6月 15 15:18:10 study.centos.vbird su[2719]: (to root) dj on pts/0
6月 15 15:18:10 study.centos.vbird su[2719]: pam_unix(su-l:session): session opened for user root by dj(uid=1000)




[root@study ~]$ journalctl -p err								找出信息严重等级为错误的信息
-- Logs begin at 一 2020-06-15 15:16:04 CST, end at 一 2020-06-15 19:20:02 CST. --
6月 15 15:16:05 study.centos.vbird kernel: sd 0:0:0:0: [sda] Assuming drive cache: write through
6月 15 15:16:16 study.centos.vbird systemd[1]: [/etc/systemd/system/backup.timer:4] Failed to parse timer value, ignoring: 2hrs
6月 15 15:16:20 study.centos.vbird kernel: piix4_smbus 0000:00:07.3: SMBus Host Controller not enabled!
6月 15 15:16:39 study.centos.vbird systemd[1]: Failed to start Crash recovery kernel arming.
...



[root@study ~]$ journalctl SYSLOG_FACILITY=4 SYSLOG_FACILITY=10			找出与登录认证服务(auth、authpriv)有关的日志文件信息
-- Logs begin at 一 2020-06-15 15:16:04 CST, end at 一 2020-06-15 19:20:02 CST. --
6月 15 15:16:30 study.centos.vbird systemd-logind[785]: New seat seat0.
6月 15 15:16:30 study.centos.vbird systemd-logind[785]: Watching system buttons on /dev/input/event0 (Power Button)
6月 15 15:16:31 study.centos.vbird polkitd[782]: Loading rules from directory /etc/polkit-1/rules.d
...

18.4.2 logger命令的应用

如果你想要让你的数据存储到日志文件中,就得使用logger这个命令。

logger	[-p 服务名称.等级]	"信息"
		


[root@study ~]$ logger -p user.info "I will check logger command"	使用logger传送数据到日志文件中
[root@study ~]$ journalctl SYSLOG_FACILITY=1 -n 3					查看一下最近的3条日志信息,发现我们添加的那句就在最新的一句日志信息
-- Logs begin at 一 2020-06-15 15:16:04 CST, end at 一 2020-06-15 19:37:58 CST. --
6月 15 15:31:42 study.centos.vbird pulseaudio[2066]: [alsa-sink-ES1371/1] alsa-sink.c: 这很可能是 ALSA 驱动程序 'snd_ens1371' 中的一个 bug。
6月 15 15:31:42 study.centos.vbird pulseaudio[2066]: [alsa-sink-ES1371/1] alsa-sink.c: 我们因 POLLOUT 被设置而唤醒 -- 但结果是 snd_pcm_avail
6月 15 19:37:58 study.centos.vbird dj[5832]: I will check logger command	看这里!!
[root@study ~]$ vim /backups/backup.sh			如果之前写的backup.service服务,想通过logger来记录备份工作的开始和结束,可以改写这个.sh文件
#!/bin/bash
if [ "${1}" == "log" ];then
        logger -p syslog.info "backup.sh is starting"
fi
source="/etc /home /root /var/lib /var/spool/{cron,at,mail}"
target="/backups/backup-system-$(date +%Y-%m-%d).tar.gz"
[ ! -d /backups  ] && mkdir /backups
tar -zcvf ${target} ${source} &> /backups/backup.log
if [ "${1}" == "log" ];then
        logger -p syslog.info "backup.sh is finished"
fi





[root@study ~]$ /backups/backup.sh log						运行备份文件
[root@study ~]$ journalctl SYSLOG_FACILITY=5 -n 3			检查一下,发现日志信息写入成功
-- Logs begin at 一 2020-06-15 15:16:04 CST, end at 一 2020-06-15 19:50:03 CST. --
6月 15 18:18:01 study.centos.vbird rsyslogd[3045]:  [origin software="rsyslogd" swVersion="8.24.0-38.el7" x-pid="3045" x-info="http://www.rs
6月 15 19:49:29 study.centos.vbird dj[5961]: backup.sh is starting	
6月 15 19:50:02 study.centos.vbird dj[5966]: backup.sh is finished

这样,我们可以将数据自行写入到日志文件中。

18.5 分析日志文件

18.5.1 CentOS默认提供的logwatch

需要另行安装logwatch软件。

18.5.2 鸟哥自己写的日志文件分析工具

鸟哥自己写的日志文件分析工具

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值