Linux下Rsyslog日志远程集中式管理
阅读原文时间:2021年07月06日阅读:1

Rsyslog简介

  • Rsyslog的全称是 rocket-fast system for log,它提供了高性能,高安全功能和模块化设计。rsyslog能够接受从各种各样的来源,将其输入,输出的结果到不同的目的地。rsyslog可以提供超过每秒一百万条消息给目标文件。
  • 日志是任何软件或操作系统的关键组件。 日志通常会记录用户的操作、系统事件、网络活动等等,具体取决于它们的用途。 Linux 系统上使用最广泛的日志系统之一是 rsyslog 。
  • Rsyslog 是一个强大、安全和高性能的日志处理系统,它接受来自不同类型源(系统/应用程序)的数据并输出为多种格式。
  • 它已经从一个常规的 syslog 守护进程发展成为一个功能齐全的企业级日志系统。 它采用客户端/服务器模型设计,因此可以配置为客户端和/或其他服务器、网络设备和远程应用程序的中央日志服务器。

功能特性:

  • 多线程
  • 可以通过许多协议进行传输UDP,TCP,SSL,TLS,RELP;
  • 直接将日志写入到数据库;
  • 支持加密协议:ssl,tls,relp
  • 强大的过滤器,实现过滤日志信息中任何部分的内容
  • 自定义输出格式

Rsyslog提供了三种远程传输协议:

  • UDP 传输协议

      基于传统UDP协议进行远程日志传输,也是传统syslog使用的传输协议; 可靠性比较低,但性能损耗最少, 在网络情况比较差, 或者接收服务器压力比较高情况下,可能存在丢日志情况。 在对日志完整性要求不是很高,在可靠的局域网环境下可以使用。

  • TCP 传输协议

      基于传统TCP协议明文传输,需要回传进行确认,可靠性比较高; 但在接收服务器宕机或者两者之间网络出问题的情况下,会出现丢日志情况。 这种协议相比于UDP在可靠性方面已经好很多,并且rsyslog原生支持,配置简单, 同时针对可能丢日志情况,可以进行额外配置提高可靠性,因此使用比较广。

  • RELP 传输协议

      RELP(Reliable Event Logging Protocol)是基于TCP封装的可靠日志消息传输协议; 是为了解决TCP 与 UDP 协议的缺点而在应用层实现的传输协议,也是三者之中最可靠的。 需要多安装一个包rsyslog-relp以支持该协议。

Rsyslog架构阐述:

    

      

环境准备

属性

Rsyslog服务器

Rsyslog客户端

节点

rsyslog-server

rsyslog-client

系统

CentOS Linux release 7.5.1804 (Minimal)

CentOS Linux release 7.5.1804 (Minimal)

内核

3.10.0-862.el7.x86_64

3.10.0-862.el7.x86_64

SELinux

setenforce 0 | disabled

setenforce 0 | disabled

IP地址

172.16.70.186

172.16.70.187

Rsyslog服务端/客户端前提设置。

[root@rsyslog-server ~]# rpm -qa | grep rsyslog
[root@rsyslog-server ~]# yum install -y rsyslog

[root@rsyslog-server ~]# rsyslogd -v # 查看版本
rsyslogd 8.24.0-57.el7_9, compiled with:
PLATFORM: x86_64-redhat-linux-gnu
PLATFORM (lsb_release -d):
FEATURE_REGEXP: Yes
GSSAPI Kerberos 5 support: Yes
FEATURE_DEBUG (debug build, slow code): No
32bit Atomic operations supported: Yes
64bit Atomic operations supported: Yes
memory allocator: system default
Runtime Instrumentation (slow code): No
uuid support: Yes
Number of Bits in RainerScript integers: 64

See http://www.rsyslog.com for more information.

[root@rsyslog-server ~]# rpm -qc rsyslog # 相关配置文件
/etc/logrotate.d/syslog
/etc/rsyslog.conf
/etc/sysconfig/rsyslog

[root@rsyslog-server ~]# setenforce 0
[root@rsyslog-server rsyslog]# getenforce
Permissive

防火墙允许tcp/udp的514端口

[root@rsyslog-server ~]# firewall-cmd --permanent --add-port=514/udp
[root@rsyslog-server ~]# firewall-cmd --permanent --add-port=514/tcp
[root@rsyslog-server ~]# firewall-cmd --reload
[root@rsyslog-server ~]# firewall-cmd --list-all
public (active)
target: default
icmp-block-inversion: no
interfaces: ens33
sources:
services: ssh dhcpv6-client
ports: 514/tcp 514/udp
protocols:
masquerade: no
forward-ports:
source-ports:
icmp-blocks:
rich rules:

默认/etc/rsyslog.conf详解。注:rsyslog官方文档:https://www.rsyslog.com/doc/v8-stable/index.html

# rsyslog v5 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 #### # 模块

$ModLoad imuxsock # provides support for local system logging (e.g. via logger command) # 支持本地系统日志记录(例如通过logger命令)
$ModLoad imjournal # provides access to the systemd journal  # 提供对systemd日志的访问
#$ModLoad imklog # provides kernel logging support (previously done by rklogd) # 提供内核日志记录支持(以前由rklogd完成)
#$ModLoad immark # provides --MARK-- message capability # 提供了--MARK--消息功能

Provides UDP syslog reception # 提供UDP系统日志接收

#$ModLoad imudp
#$UDPServerRun 514

Provides TCP syslog reception # 提供TCP系统日志接收

#$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/ # 将所有配置文件包含在/etc/rsyslog.d/中

$IncludeConfig /etc/rsyslog.d/*.conf

Turn off message reception via local log socket;  # 关闭本地日志消息,使用imjournal

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

记录info级别的日志信息 排除mail authpriv cron

The authpriv file has restricted access. # authpriv文件具有受限制的访问权限。

authpriv.* /var/log/secure

Log all the mail messages in one place. # 将所有的邮件记录在一个地方。

mail.* -/var/log/maillog

-/var/log/maillog 前面"-"是:代表异步写入,邮件量大占I/O在系统不忙时做

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

Save boot messages also to boot.log # 将启动信息保存到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.

#$WorkDirectory /var/lib/rsyslog # where to place spool files
#$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 ### 转发规则结束

情景一:收集主机的crond,history的日志转发到rsyslog服务端上做备份。

步骤1.Rsyslog服务端操作
[root@rsyslog-server ~]# cp /etc/rsyslog.conf /etc/rsyslog.conf_bak
[root@rsyslog-server ~]# cat /etc/rsyslog.conf

MODULES ####

$ModLoad imuxsock # provides support for local system logging (e.g. via logger command)
$ModLoad imjournal # provides access to the systemd journal

开启udp 514

$ModLoad imudp
$UDPServerRun 514

开启tcp 514

$ModLoad imtcp
$InputTCPServerRun 514

GLOBAL DIRECTIVES ####

$WorkDirectory /var/lib/rsyslog
$ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat
$IncludeConfig /etc/rsyslog.d/*.conf
$OmitLocalLogging on
$IMJournalStateFile imjournal.state

RULES ####

*.info;mail.none;authpriv.none;cron.none /var/log/messages
authpriv.* /var/log/secure
mail.* -/var/log/maillog
cron.* /var/log/cron
*.emerg :omusrmsg:*
uucp,news.crit /var/log/spooler
local7.* /var/log/boot.log

新增内容

$template local1_path, "/data/rsyslog/%FROMHOST-IP%/history/%$YEAR%-%$MONTH%-%$DAY%.log"
if $fromhost-ip != '127.0.0.1' and $syslogfacility-text == 'local1' then ?local1_path
& ~

$template remote_path, "/data/rsyslog/%FROMHOST-IP%/%syslogfacility-text%/%$YEAR%-%$MONTH%-%$DAY%.log"
if $fromhost-ip != '127.0.0.1' then ?remote_path
& ~

验证配置文件是否正确

[root@rsyslog-server ~]# rsyslogd -f /etc/rsyslog.conf -N8    //其中,-N后面的数值代表rsyslog的版本。

配置解析:
  格式::
    日志设备(类型).(连接符号)日志级别 日志处理方式(action)
1.日志级别
debug 有调式信息的,日志信息最多
info 一般信息的日志,最常用
notice 最具有重要性的普通条件的信息
warning 警告级别
err 错误级别,阻止某个功能或者模块不能正常工作的信息
crit 严重级别,阻止整个系统或者整个软件不能正常工作的信息
alert 需要立刻修改的信息
emerg 内核崩溃等严重信息
none 什么都不记录
   local 1~7 自定义的日志设备
从上到下,级别从低到高,记录的信息越来越少

2.连接符号
.xxx :表示大于等于xxx级别的信息
.=xxx:表示等于xxx级别的信息
.!xxx:表示在xxx之外的等级的信息

3.Actions
记录到普通文件或设备文件:
. /var/log/file.log # 绝对路径
. /dev/pts/0
logger 命令用于产生日志: logger -p local3.info 'KadeFor is testing the rsyslog and logger'

  转发到远程::
. @172.16.0.1 # 使用UDP协议转发到172.16.0.1的514(默认)端口
. @@172.16.0.1:10514 # 使用TCP协议转发到172.16.0.1的10514(默认)端口

发送给用户(需要在线才能收到)::  
. root  
. root,kadefor,up01 # 使用,号分隔多个用户  
. \* # \*号表示所有在线用户

忽略,丢弃::  
local3.\* ~ # 忽略所有local3类型的所有级别的日志

执行脚本::  
local3.\* ^/tmp/a.sh # ^号后跟可执行脚本或程序的绝对路径  
# 日志内容可以作为脚本的第一个参数. 可用来触发报警  
注意: 日志记录的顺序有先后关系!

 自定义模板
  $template定义了两个模板,名称分别为local1_path和remote_path,模板名称后面指定了将消息保存到的日志文件的路径。
  if开头的指令是基于表达式的过滤器。第一条if指令的意思是,如果日志消息的来源IP地址不是本机,且消息的syslogfacility-text为local1,那么将这条消息写入由模板local1_path对应的文件。
  & ~的含义是让满足上面过滤器条件的消息不再匹配后续的规则。默认情况下,日志消息会按顺序匹配rsyslog.conf中的每条规则。& ~在这里会让消息跳过后面的规则,这样这条消息就不会再被写入其他的日志文件了。
  第二条if开头的指令将来自于本机之外的所有日志消息(由于前面的& ~,满足这个条件的只有auth、authpriv和cron消息)写入remote_path所对应的文件。

[root@rsyslog-server ~]# systemctl restart rsyslog
[root@rsyslog-server ~]# netstat -auntpl | grep rsyslog
tcp 0 0 0.0.0.0:514 0.0.0.0:* LISTEN 1351/rsyslogd
tcp6 0 0 :::514 :::* LISTEN 1351/rsyslogd
udp 0 0 0.0.0.0:514 0.0.0.0:* 1351/rsyslogd
udp6 0 0 :::514 :::* 1351/rsyslogd
[root@rsyslog-server ~]# mkdir -p /data/rsyslog/
[root@rsyslog-server ~]# ls -ld /data/rsyslog/
drwxr-xr-x. 2 root root 6 Jun 9 10:06 /data/rsyslog

步骤2.rsyslog客户端操作
root@rsyslog-client ~]# cp /etc/rsyslog.conf /etc/rsyslog.conf_bak

在/etc/rsyslog.conf最尾行添加内容

[root@rsyslog-client ~]# sed -i '$acron.* @@172.16.70.186:514\nlocal1.notice @@172.16.70.186:514' /etc/rsyslog.conf
[root@rsyslog-client ~]# tail -2 /etc/rsyslog.conf
cron.* @@172.16.70.186:514
local1.notice @@172.16.70.186:514

[root@rsyslog-client ~]#rsyslogd -f /etc/rsyslog.conf -N8

在/etc/crontab最尾行添加内容

[root@rsyslog-client ~]# sed -i '$a* * * * * root ls -l /etc /var/log' /etc/crontab
[root@rsyslog-client ~]# tail -1 /etc/crontab
* * * * * root ls -l /etc /var/log

在/etc/profile最尾行添加内容

[root@rsyslog-client ~]# tail -2 /etc/profile
export HISTTIMEFORMAT
export PROMPT_COMMAND='{ command=$(history 1 | { read x y; echo $y; }); logger -p local1.notice -t bash -i "user=$USER,ppid=$PPID,from=$SSH_CLIENT,pwd=$PWD,command:$command"; }'
[root@rsyslog-client ~]# source /etc/profile

[root@rsyslog-client ~]# systemctl restart crond rsyslog

history Server端验证作用

[root@rsyslog-client ~]# ls -l /etc/
[root@rsyslog-client ~]# ls -la /var/log/

步骤3.rsyslog服务端验证
[root@rsyslog-server ~]# cd /data/rsyslog/
[root@rsyslog-server rsyslog]# tree ./
./
└── 172.16.70.187
├── cron
│ └── 2021-06-11.log
└── history
└── 2021-06-11.log
若无生成log,Server端,Client端各重启几遍rsyslog即可。

[root@rsyslog-server rsyslog]# tail 172.16.70.187/cron/2021-06-11.log
Jun 11 10:48:01 rsyslog-client CROND[9085]: (root) CMD (ls -l /etc /var/log)
Jun 11 10:49:01 rsyslog-client CROND[9090]: (root) CMD (ls -l /etc /var/log)
Jun 11 10:50:01 rsyslog-client CROND[9095]: (root) CMD (ls -l /etc /var/log)
Jun 11 10:51:01 rsyslog-client CROND[9100]: (root) CMD (ls -l /etc /var/log)

[root@rsyslog-server rsyslog]# tail 172.16.70.187/history/2021-06-11.log
Jun 11 10:54:07 rsyslog-client bash[9158]: user=root,ppid=1287,from=172.16.70.187 11930 22,pwd=/root,command:ls -l /etc/
Jun 11 10:54:14 rsyslog-client bash[9163]: user=root,ppid=1287,from=172.16.70.187 11930 22,pwd=/root,command:ls -la /var/log/

情景二:收集主机的应用服务的日志转发到rsyslog服务端上做备份。

步骤1.Rsyslog服务端
[root@rsyslog-server ~]# cat /etc/rsyslog.conf

MODULES ####

$ModLoad imuxsock # provides support for local system logging (e.g. via logger command)
$ModLoad imjournal # provides access to the systemd journal

$ModLoad imudp
$UDPServerRun 514

$ModLoad imtcp
$InputTCPServerRun 514

GLOBAL DIRECTIVES ####

$WorkDirectory /var/lib/rsyslog
$ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat
$IncludeConfig /etc/rsyslog.d/*.conf
$OmitLocalLogging on
$IMJournalStateFile imjournal.state

RULES ####

*.info;mail.none;authpriv.none;cron.none /var/log/messages
authpriv.* /var/log/secure
mail.* -/var/log/maillog
cron.* /var/log/cron
*.emerg :omusrmsg:*
uucp,news.crit /var/log/spooler
local7.* /var/log/boot.log

$template HttpAccess,"%msg%\n"
$template AccessFile,"/data/rsyslog/%FROMHOST-IP%/httpd/http-access.log"
$template HttpError,"%msg%\n"
$template ErrorFile,"/data/rsyslog/%FROMHOST-IP%/httpd/http-error.log"

user.* ?AccessFile;HttpAccess
user.* ?ErrorFile;ErrorFile

[root@rsyslog-server ~]# systemctl restart rsyslog
[root@rsyslog-server ~]# mkdir /data/rsyslog

步骤2.Rsyslog客户端
[root@rsyslog-client ~]# yum install -y hpptd
[root@rsyslog-client ~]# systemctl start httpd
[root@rsyslog-client ~]# netstat -nutpl | grep httpd
tcp6 0 0 :::80 :::* LISTEN 9225/httpd

apache日志文件路径

[root@rsyslog-client ~]# ls -l /var/log/httpd/*
-rw-r--r--. 1 root root 43059 Jun 11 16:38 /var/log/httpd/access_log
-rw-r--r--. 1 root root 8823 Jun 11 16:38 /var/log/httpd/error_log

[root@rsyslog-client ~]# cp /etc/rsyslog.conf /etc/rsyslog.conf_bak
[root@rsyslog-client ~]# vim /etc/rsyslog.conf
….

最末行添加

$ModLoad imfile    # 加载imfile模块

$InputFileName /var/log/httpd/access_log    
$InputFileTag apache_access           
$InputFileStateFile apache-access       

$InputFileName var/log/httpd/error_log
$InputFileTag apache_error
$InputFileStateFile apache-error

$InputFileSeverity info
$InputFileFacility user
$InputFilePollInterval 1
$InputFilePersistStateInterval 1
$InputRunFileMonitor
user.* @172.16.70.186

配置解析:
  $InputFileName           # 访问应用日志文件路径
  $InputFileTag            # tag 标签,可用作过滤或分类 
  $InputFileStateFile        # 状态文件,只需要指定文件名,程序会在工作目录$WorkDirectory下创建指定文件

  $InputFileSeverity         # 日志级别
  $InputFileFacility         # 日志类型,user代表应用日志
  $InputFilePollInterval       # 频率轮询新数据,单位秒
  $InputFilePersistStateInterval  # 写入状态文件时间间隔,单位秒
  $InputRunFileMonitor        # 激活当前监视器
  user.* @172.16.70.186       # 接收服务器IP

root@rsyslog-client ~]# systemctl restart rsyslog

步骤3.rsyslog服务端验证
在任意Window 10主机浏览器访问rsyslog客户端apache服务
 http://172.16.70.187    # 正确访问会生成access.log
 http://172.16.70.187:808  # 错误访问会生成error.log

[root@rsyslog-server ~]# cd /data/rsyslog
[root@rsyslog-server rsyslog]# tree
.
└── 172.16.70.187
└── httpd
├── http-access.log
└── http-error.log

注:若无生成log,Server端,Client端各重启几遍rsyslog即可。