rsyslog管理分布式日志

发布时间:2020-08-11 11:06:53 作者:sshpp
来源:网络 阅读:350

背景

有一个4台机器的分布式服务,不多不少,上每台机器上查看日志比较麻烦,用Flume,Logstash、ElasticSearch、Kibana等分布式日志管理系统又显得大材小用,所以想到了centos自带的rsyslog。

简介

Rsyslog可以简单的理解为syslog的超集,在老版本的Linux系统中,Red Hat Enterprise Linux 3/4/5默认是使用的syslog作为系统的日志工具,从RHEL 6 开始系统默认使用了Rsyslog。

Rsyslog 是负责收集 syslog 的程序,可以用来取代 syslogd 或 syslog-ng。 在这些 syslog 处理程序中,个人认为 rsyslog 是功能最为强大的。 其特性包括:

版本查看

$rsyslogd -version
rsyslogd 3.22.1, compiled with:    FEATURE_REGEXP:             Yes    FEATURE_LARGEFILE:          Yes
    FEATURE_NETZIP (message compression):   Yes
    GSSAPI Kerberos 5 support:      Yes
    FEATURE_DEBUG (debug build, slow code): No
    Atomic operations supported:        Yes
    Runtime Instrumentation (slow code):    NoSee http://www.rsyslog.com for more information.

安装

yum -y rsyslog#查看是否安装了rsyslogrpm -qa | grep rsyslog#如果还需要别的组件(mysql模块,日志轮转)yum -y rsyslog-mysql  
yum -y logrotate

启动/停止

/etc/init.d/rsyslog start/etc/init.d/rsyslog stop/etc/init.d/rsyslog restart

//帮助文档 man rsyslogd, 或者输入一个错误的命令
$rsyslogd --helprsyslogd: invalid option -- '-'usage: rsyslogd [-c<version>] [-46AdnqQvwx] [-l<hostlist>] [-s<domainlist>]
                [-f<conffile>] [-i<pidfile>] [-N<level>] [-M<module load path>]
                [-u<number>]To run rsyslogd in native mode, use "rsyslogd -c3 <other options>"For further information see http://www.rsyslog.com/doc

配置

rsyslog的配置文件有多种书写方法:

在本文中的配置都比较简单,就采用了legacy rsyslog的配置书写方法。更多详情参考:http://www.rsyslog.com/doc/master/configuration/basic_structure.html#statement-types

配置文件简单实例

下面是一个例子:

$less /etc/rsyslog.conf 
#rsyslog v3 config file# if you experience problems, check# http://www.rsyslog.com/troubleshoot for assistance#### MODULES ####$ModLoad imuxsock.so    # provides support for local system logging (e.g. via logger command)$ModLoad imklog.so      # provides kernel logging support (previously done by rklogd)#$ModLoad immark.so     # provides --MARK-- message capability# Provides UDP syslog reception#$ModLoad imudp.so#$UDPServerRun 514# Provides TCP syslog reception#$ModLoad imtcp.so  #$InputTCPServerRun 514#### GLOBAL DIRECTIVES ##### 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#### 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 stuffcron.*                                                  /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.loglocal7.*                                                /var/log/boot.log

配置文件模块

配置文件查看less /etc/rsyslog.conf。Rsyslog的配置主要有以下模块:

常用的modules

规则(rules)

规则的选择器(selectors)

selector也由两部分组成,设施和优先级,由点号.分隔。第一部分为消息源或称为日志设施,第二部分为日志级别。多个选择器用;分隔,如:*.info;mail.none

日志设施有:

日志级别有(升序):

日志设施的配置:

对于多个选择器可以用;分隔。

local0.=debug                /home/admin/applogs/app-name/debug.loglocal0.err;local0.warning;local0.info                /home/admin/applogs/app-name/info.loglocal0.err                /home/admin/applogs/app-name/error.log
动作 (action)

action是规则描述的一部分,位于选择器的后面,规则用于处理消息。总的来说,消息内容被写到一种日志文件上,但也可以执行其他动作,比如写到数据库表中或转发到其他主机。

在前面的实例中的是写到本地文件中的:

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

也可以写到mysql数据库中,

# modules, 要将日志写到mysql中需要加载ommysql模块$ModLoad ommysql 
# rule, send to mysql#*.*       :ommysql:database-server,database-name,database-userid,database-password*.*       :ommysql:127.0.0.1,Syslog,syslogwriter,topsecret

关于配置发送消息到数据库的更多类容可以参考:http://www.rsyslog.com/doc/master/tutorials/database.html

action的配置:


模板(templates)

模板允许你指定日志信息的格式,也可用于生成动态文件名,或在规则中使用。其定义如下所示,其中TEMPLATE_NAME是模板的名字,PROPERTY是rsyslog本身支持的一些属性参数。

$template TEMPLATE_NAME,"text %PROPERTY% more text", [OPTION]

使用例子:

$template DynamicFile,"/var/log/test_logs/%timegenerated%-test.log"$template DailyPerHostLogs,"/var/log/syslog/%$YEAR%/%$MONTH%/%$DAY%/%HOSTNAME%/messages.log"*.info ?DailyPerHostLogs
*.* ?DynamicFile

在模板中我们用到的properties可以参考官方文档说明,例子中用到的timegenerated是指接收到消息时的时间戳。

输出(outputs)

输出频道为用户可能想要的输出类型提供了保护,在规则中使用前要先定义.其定义如下所示,其中NAME指定输出频道的名称,FILE_NAME指定输出文件,MAX_SIZE指定日志文件的大小,单位是bytes, ACTION指定日志文件到达MAX_SIZE时的操作。

$outchannel NAME, FILE_NAME, MAX_SIZE, ACTION

在规则中使用输出频道按照如下的格式:

selectors :omfile:$NAME

例子:

$outchannel log_rotation, /var/log/test_log.log, 104857600, /home/joe/log_rotation_script

*.* :omfile:$log_rotation

配置的验证

通过下面命令可以校验配置文件是否配置正确:

sudo rsyslogd -f /etc/rsyslog.conf -N4

其中 -N后面的数值代表rsyslog启动时-c 后指定的版本。

通过下面命令可以手动发送日志信息:

logger -p local0.info "hello world"

日志文件Rotating

随着日志文件越来越大,这不仅会带来性能问题,同时对日志的管理也非常棘手。 当一个日志文件被rotated,会创建一个新的日志文件,同时旧的日志文件会被重命名。这些文件在一段时间内被保留,一旦产生一定数量的旧的日志,系统就会删除一部分旧的日志。

logrotate配置文件实例

logrotate是通过cron任务调用的,在安装的时候就自动创建了,所以通过ps命令看不到logrotate,可查看定时任务调用:cat /etc/cron.daily/logrotate

#!/bin/sh/usr/sbin/logrotate /etc/logrotate.conf >/dev/null 2>&1
EXITVALUE=$?if [ $EXITVALUE != 0 ]; then
    /usr/bin/logger -t logrotate "ALERT exited abnormally with [$EXITVALUE]"fiexit 0

cron.daily下的文件执行都是通过/etc/crontab配置的:

$cat /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/# For details see man 4 crontabs# Example of job definition:# .---------------- minute (0 - 59)# |  .------------- hour (0 - 23)# |  |  .---------- day of month (1 - 31)# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat# |  |  |  |  |# *  *  *  *  * user-name command to be executed0 0 * * * root run-parts /etc/cron.daily #定时执行cron.daily

logrotate的配置文件为/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 onescreate# uncomment this if you want your log files compressed
#compress# packages drop log rotation information into this directoryinclude /etc/logrotate.d# no packages own wtmp, or btmp -- we'll rotate them here/var/log/syslog
{
    rotate 7
    daily
    missingok
    notifempty
    delaycompress    compress
    postrotate
        invoke-rc.d rsyslog reload > /dev/null
    endscript
}
/var/log/cron.log/var/log/debug
/var/log/messages
{
    rotate 4
    weekly
    missingok
    notifempty    compress
    delaycompress
    sharedscripts
    postrotate
        invoke-rc.d rsyslog reload > /dev/null
    endscript
}
# system-specific logs may be configured here

syslog的日志文件每天被rotated,保留7份旧的日志。其他的日志文件每周进行一次rotate,并保留4份旧的日志。

logrotate配置项

我们可以通过man logrotate来获取所有的参数和详细描述。这里列出一部分:

实例

sudo vim /etc/rsyslog.conf

# Provides UDP syslog reception$ModLoad imudp.so
$UDPServerRun 514$template ipAndMsg,"[%fromhost-ip%]  %$now%%msg%\n"local0.=debug                /home/admin/applogs/app-name/debug.log;ipAndMsglocal0.err;local0.warning;local0.info                /home/admin/applogs/app-name/info.log;ipAndMsglocal0.err                /home/admin/applogs/app-name/error.log;ipAndMsg

sudo service rsyslog restart

sudo service syslog/syslog-ng stop

sudo vim /etc/logrotate.conf

/home/admin/applogs/app-name/debug.log/home/admin/applogs/app-name/info.log/home/admin/applogs/app-name/error.log{
    daily
    create 0664 root root
    rotate 30
    missingok
    nocompress
    notifempty
    dateext
    postrotate        /etc/init.d/rsyslog restart > /dev/null 2>&1
    endscript
}

注意,最后必须加上:

postrotate        /etc/init.d/rsyslog restart > /dev/null 2>&1endscript

因为logrotate之后,即使已经移走了,但是rsyslog还是持有这个文件操作句柄,会继续往原文件(被rotate的文件)中写,即使已经被重命名了,所以需要 restart rsyslog 来 reopen 下 logrotate新创建的同名文件。

另外有一个可以不用重启的办法,但是会丢失部分数据,logrotate 提供了 copytruncate。默认的指令 create 做法,是 移动旧文件,创建新文件,然后用脚本reopen新文件;而 copytruncate 是采用的先拷贝再清空, 先复制一份旧的日志,然后请客原文件,整个过程原来的文件句柄,并没有变化,所以不需要reopen,服务可以不中断,但是这个过程会导致部分数据丢失。


推荐阅读:
  1. 日志管理-rsyslog
  2. Rsyslog+Loganalyer+MySQL下部署日志服务器

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

rsyslog sys%

上一篇:解决有光标黑屏任务管理器进不去的方法

下一篇:Check all partioned tables & Indexes

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》