rsyslog配置文件详解(常用的详解,很少用的翻官网罢)--适用v7/v8版本

主配置文件位置:/etc/rsyslog.conf


去除部分注释内容

#### MODULES ####             #定义日志的模块,远程日志的配置也在这(我个人习惯,在配置服务器的时候用于接受日志的template,rulesets,input和allowsender都是写在这个模块下的,测试可用)

$ModLoad imuxsock             #imuxsock模块,支持本地系统日志的模块
$ModLoad imjournal            #imjournal模块,支持对系统日志的访问(此模块与上一模块默认启用)
#$ModLoad imklog              #imklog模块,支持内核日志的模块
#$ModLoad immark              #immark模块,支持日志标记

# Provides UDP syslog reception    #提供远程rsyslog日志的udp协议的接收支持
# $ModLoad imudp                   #imudp模块,用于支持udp协议
# $UDPServerRun 514                #允许通过514端口接收使用udp协议的远程日志
# Provides TCP syslog reception    #提供远程rsyslog日志的tcp协议的接收支持
# $ModLoad imtcp                   #imtcp模块,用于支持tcp协议
# $InputTCPServerRun 514           #允许通过514端口接收使用tcp协议的远程日志

#### GLOBAL DIRECTIVES ####    #定义全局日志格式的指令

# Where to place auxiliary files
$WorkDirectory /var/lib/rsyslog       #工作目录

# Use default timestamp format
$ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat   #定义日志格式默认模板(可以自行设定,参看template部分)

# $ActionFileEnableSync on                             #文件同步功能,很少用,默认禁止

# Include all conifig files in /etc/rsyslog.d/
$IncludeConfig /etc/rsyslog.d/*.conf                   #需要引入的自定义配置文件的路径

$OmitLocalLogging on                                      #关闭通过本地日志接口接收消息,现使用imjournal模块作为替代

# File to store the position in the journal
$IMJournalStateFile imjournal.state                   #见英文注释,用的不多,暂时不管

#### RULES ####

# 内核消息,默认不启用
# kern.*                                  /dev/console

# 记录所有日志类型的,信息等级大于等于info级别的信息到messages文件(mail邮件信息,authpriv验证信息和corn时间和任务信息除外)
*.info;mail.none;authpriv.none;cron.none      /var/log/messages

# authpriv验证相关的所有信息存放在/var/log/secure
authpriv.*                                /var/log/secure

# 邮件的所有信息存在/var/log/maillog;这里有一个“-”符号表示是使用异步的方式记录
mail.*                                   -/var/log/maillog

# 任务计划有关的信息存放在/var/log/cron
cron.*                                   /var/log/cron

# 记录所有的≥emerg级别信息,发送给每个登录到系统的日志
*.emerg                                 :omusrmsg:*

# 记录uucp,news.crit等存放在/var/log/spooler
uucp,news.crit                            /var/log/spooler

# 本地服务器的启动的所有日志存放在/var/log/boot.log
local7.*                                  /var/log/boot.log

#### begin forwarding rule ####               #远程转发的配置,只要去除转发配置前面的注释就可使用。不用去除modules部分imtcp/imudp的注释,不必修改上面的任何配置。
#日志发送的配置,@表示传输协议(@表示udp,@@表示tcp),后面是ip和端口,格式可配置
#*.* @@remote-host:514
#### end of the forwarding rule ####

配置语言格式

        基础格式,即最简单的配置格式,没有任何多余的功能,配置中默认的内容即为此格式:

# 邮件的所有信息存在/var/log/maillog;这里有一个“-”符号表示是使用异步的方式记录
mail.*                                   -/var/log/maillog
# 邮件的错误信息转发到server.example.com,使用tcp连接(@@)
mail.error                                @@server.example.com

        高级格式,支持更多模块,更多参数,更多选项,并且允许对日志格式,内容等进行自定义修改的格式,是v8版本所推荐的格式:

# 邮件的所有信息存在/var/log/maillog;这里有一个“-”符号表示是使用异步的方式记录
mail.* action(type="omfile" File="/var/log/maillog")
# 邮件的错误信息转发到server.example.com,使用tcp连接(@@)
mail.error  action(type="omfwd" Target="server.example.com" Port="10514" Protocol="tcp")

        注意:基础格式和高级格式可以混合使用。但是在使用中,存在很多过时的语法参数等内容(尤其是网上查找到的资料中使用基础格式的时候),一般不建议使用这些过时的配置,但是这些格式仍可被识别(为了兼容性和稳定性考虑),但会在执行中出现一些关于配置格式的提醒。关于哪些东西是被视为过时的内容,请查找参考官网https://www.rsyslog.com文档中标记为obsolete legacy的部分。


数据格式化:template(自定义路径/文件名也是这个)

template(name="MyFormat" type="list") {                  # 类型有list,subtree,string,plugin四种,list最常用,string也可以,其余少见
     constant(value="Syslog MSG is: '")          # constant是日志文本的静态部分
     property(name="msg")                        # property用来引入日志信息中的特定属性的部分,例如此处会自动获取每条日志的msg部分并填入日志文本中
     constant(value="', ")
     property(name="timereported" dateFormat="rfc3339" caseConversion="lower")    # 时间属性,在文本中加入时间信息,后面的两个参数是用于该属性的参数,根据前面的属性填写
	 property(name="timereported" dateformat="year")    # 单独提取年月日写入文本
     constant(value="-")
     property(name="timereported" dateformat="month")
     constant(value="-")
     property(name="timereported" dateformat="day")
     constant(value="\n")
     }

        以上是一个标准的格式化用法(高级格式),因为操作性强兼容性好,里面的property在最后附上(英文的,简单看看,能懂)
        另外附上string类型的写法:

template(name="tpl3" type="string"
         string="%TIMESTAMP:::date-rfc3339% %HOSTNAME% %syslogtag%%msg:::sp-if-no-1st-sp%%msg:::drop-last-lf%\n"
        )

        里面的property均用%property%形式表示,参数也写在里面,适合一些日志内容、格式较为简单的场合。
        用法(action用法在下面):

action(type="omfwd" target="server1.example.net" template=“TemplateName”)
mail.*  /var/log/maillog;TemplateName         # 使用;分割,后接定义好的template  
*.*     @@remote-host;TemplateName

文件目录自定义

$template DynaFileName,”/var/log/%fromhost-ip%/%programname%_%$YEAR%-%$MONTH%-%$DAY%.log”

        实际上这是一种 过时的 string类型的Template(并且只支持string类型),因此相应的也可以更改成高级格式。里面的%property%同高级格式的Template一样根据需要自由引入,使用方法如下:

*.*    -?DynaFileName                # 所有日志发送到DynaFileName定义的文件中,注意自定义文件名(的Template名字)前需要有?符号
:fromhost-ip, !isequal, "127.0.0.1"    ?DynaFileName           # 所有来源非本机的日志发送到DynaFileName定义的文件中,注意自定义文件名(的Template名字)前需要有?符号

        如果需要对日志格式进行自定义,则需要参考前面Template的配置格式引入,如下:

*.*    -?DynaFileName;MyTemplate      # 所有日志发送到DynaFileName定义的路径文件中,使用MyTemplate进行格式处理 

        另外Template支持生成json等格式的日志,可根据需要加入参数以使用。具体使用请参见官网文档:https://www.rsyslog.com/doc/v8-stable/configuration/templates.html


简单过滤:filter

标注用法:

:property, [!]compare-operation, "value"

property不多说,compare-operation是判断操作(加!取反),value跟的是用来判断的值。compare-operation有以下这些(挺简单的,自己翻译一下):

contains
    Checks if the string provided in value is contained in the property. There must be an exact match, wildcards are not supported.

isequal
    Compares the “value” string provided and the property contents. These two values must be exactly equal to match. The difference to contains is that contains searches for the value anywhere inside the property value, whereas all characters must be identical for isequal. As such, isequal is most useful for fields like syslogtag or FROMHOST, where you probably know the exact contents.

startswith
    Checks if the value is found exactly at the beginning of the property value. For example, if you search for “val” with
    :msg, startswith, "val"
    it will be a match if msg contains “values are in this message” but it won’t match if the msg contains “There are values in this message” (in the later case, “contains” would match). Please note that “startswith” is by far faster than regular expressions. So even once they are implemented, it can make very much sense (performance-wise) to use “startswith”.
    
regex
    Compares the property against the provided POSIX BRE regular expression.
    
ereregex
    Compares the property against the provided POSIX ERE regular expression.

        还有一种基于复杂表达式的filter,可以使用and等命令连接多个判断式,达到相对复杂的判断逻辑:

if expr then action-part-of-selector-line

        例子:

if $syslogfacility-text == 'local0' and $msg startswith 'DEVNAME' and not ($msg contains 'error1' or $msg contains 'error0') then /var/log/somelog

数据处理:action

        就是怎么处理数据,例子如下:

action(type="omfwd" target="server1.example.net" ...)          #  将数据转发到server1.example.net去,默认端口514,后面根据需要添加其他参数

        其中type定义了处理数据所使用的模块,有多个模块可选择,具体模块和参数介绍可以在官网output module:https://www.rsyslog.com/doc/v8-stable/configuration/modules/idx_output.html找到。后面的target等均为模块所用参数,可自行查找。
        需要注意的是,action在基础格式中可以直接使用,但是这种使用经常会和其他传统格式的配置混在在一块导致一些配置不明朗,会造成误解。例如:

$actionResumeRetryCount 10     # 参数配置,连接重试次数为10
action(type="omfwd" target="server1.example.net")  # 前面的参数对action不生效,因为action内部没有该参数,只有action内指定的参数有效
@@server2.example.net          # 将数据转发到server2.example.net去,默认端口514,前面指定的10次重试次数对该配置有效

        所以在使用基础格式的适合优先建议将相关的配置代码都聚合在一起使用,并且需要格外注意配置项目的相关性/影响性等(就像例子中那样)。或者干脆使用高级格式进行配置。


复杂数据过滤:rulesets

ruleset(name="Remote"){
    if prifilt("mail.*") then {
        action(type="omfile" file="/var/log/remotefile")
        stop             #此处的stop在之前版本里是“~”,代表抛弃数据不进行下一步处理,在老版本语法里写为“&~”,&为命令连接符号。v7/v8也可以这么用,但是会有一个警告说语法已经更新,请上官网查看,这个不会影响正常运行可以忽略
        # note that the stop-command will prevent this message from
        # being written to the remotefile - as usual...
    }
    if $programname == "sshd" and prifilt("*.err") then {
        :fromhost-ip, !isequal, "127.0.0.1" ?DynFileName
    }
}

        用法基本如此,可以灵活使用上面template,filter,action的语法,达到复杂的判断和数据处理的目的。用法参看下面的input


数据来源:input

        这个没啥好说的,用法类似与action,如下:

input(type="imptcp" port="514" ruleset="Remote")

其中type为使用的数据来源模块,port等为模块参数,ruleset为所使用的ruleset。type中的模块有多种,可在官网input module:https://www.rsyslog.com/doc/v8-stable/configuration/modules/idx_input.html找到相关简介和参数说明。


其他

        rsyslog还支持很多其他的用法,例如数据传输的加密,引入其他模块之类的功能,但是因为我的主要目的是完成一个日志客户端和服务端的搭建通信功能,所以只把相关部分的配置进行了研究和记录。如果需要使用其他功能的话,建议前往官网自行查找相关资料(写说明的歪果仁挺口语化的,写了不少内容,需要慢慢看,提取有效资料)。

        另外吐槽一句:之前查资料,v7/v8版本语法的资料实在是太少了,都是老版语法的资料(在v7/v8上配置完运行时候会报一个警告,说语法已经更新了,请前去官网查看什么的,但是可以正常运行不会报错),而且是各种地方互相抄,一个文章看N遍。。。。。。最后只能自己去官网找了。
        希望能帮到大家。


更新

        重新更新了一些配置说明的内容。值得一提的是,官网现在格式化做的真不错,v5、v7、v8的配置说明都是独立的,里面的说明也很详细,非常易于阅读和理解。优先建议大家上官网查询资料,尤其是本文章中找不到你需要的东西的时候。
v8版本的官网地址https://www.rsyslog.com/doc/v8-stable/
        其他的版本在 官网 > HELP > Documentation > vX-stable下面,进去自己找吧


附录:property ( in English)

Message Properties:
        These are extracted by rsyslog parsers from the original message. All message properties start with a letter.

The following message properties exist:

msg
        the MSG part of the message (aka “the message” ; ))

rawmsg
        the message excactly as it was received from the socket. Should be useful for debugging.

hostname
        hostname from the message

source
        alias for HOSTNAME

fromhost
        hostname of the system the message was received from (in a relay chain, this is the system immediately in front of us and not necessarily the original sender). This is a DNS-resolved name, except if that is not possible or DNS resolution has been disabled.

fromhost-ip
        The same as fromhost, but alsways as an IP address. Local inputs (like imklog) use 127.0.0.1 in this property.

syslogtag
        TAG from the message

programname
        the “static” part of the tag, as defined by BSD syslogd. For example, when TAG is “named[12345]”, programname is “named”.

pri
        PRI part of the message - undecoded (single value)

pri-text
        the PRI part of the message in a textual form with the numerical PRI appended in brackes (e.g. “local0.err<133>”)

iut
        the monitorware InfoUnitType - used when talking to a MonitorWare backend (also for Adiscon LogAnalyzer)

syslogfacility
        the facility from the message - in numerical form

syslogfacility-text
        the facility from the message - in text form

syslogseverity
        severity from the message - in numerical form

syslogseverity-text
        severity from the message - in text form

syslogpriority
        an alias for syslogseverity - included for historical reasons (be careful: it still is the severity, not PRI!)

syslogpriority-text
        an alias for syslogseverity-text

timegenerated
        timestamp when the message was RECEIVED. Always in high resolution

timereported
        timestamp from the message. Resolution depends on what was provided in the message (in most cases, only seconds)

timestamp
        alias for timereported

protocol-version
        The contents of the PROTCOL-VERSION field from IETF draft draft-ietf-syslog-protcol

structured-data
        The contents of the STRUCTURED-DATA field from IETF draft draft-ietf-syslog-protocol

app-name
        The contents of the APP-NAME field from IETF draft draft-ietf-syslog-protocol

procid
        The contents of the PROCID field from IETF draft draft-ietf-syslog-protocol

msgid
        The contents of the MSGID field from IETF draft draft-ietf-syslog-protocol

inputname
        The name of the input module that generated the message (e.g. “imuxsock”, “imudp”). Note that not all modules necessarily provide this property. If not provided, it is an empty string. Also note that the input module may provide any value of its liking. Most importantly, it is not necessarily the module input name. Internal sources can also provide inputnames. Currently, “rsyslogd” is defined as inputname for messages internally generated by rsyslogd, for example startup and shutdown and error messages. This property is considered useful when trying to filter messages based on where they originated - e.g. locally generated messages (“rsyslogd”, “imuxsock”, “imklog”) should go to a different place than messages generated somewhere.


System Properties:
        These properties are provided by the rsyslog core engine. They are not related to the message. All system properties start with a dollar-sign.
        For example, timereported contains the timestamp from the message. Depending on how long the message was in the relay chain, this can be quite old. In contrast, $now is the system time when the message is being processed. Depending on your needs, you need one or the other. Usually, the message-based timestamp is the more important one, but that really depdends on the use case.

The following system properties exist:

$bom
        The UTF-8 encoded Unicode byte-order mask (BOM). This may be useful in templates for RFC5424 support, when the character set is know to be Unicode.

$now
        The current date stamp in the format YYYY-MM-DD

$year
        The current year (4-digit)

$month
        The current month (2-digit)

$day
        The current day of the month (2-digit)

$hour
        The current hour in military (24 hour) time (2-digit)

$hhour
        The current half hour we are in. From minute 0 to 29, this is always 0 while from 30 to 59 it is always 1.

$qhour
        The current quarter hour we are in. Much like $HHOUR, but values range from 0 to 3 (for the four quater hours that are in each hour)

$minute
        The current minute (2-digit)

$myhostname
        The name of the current host as it knows itself (probably useful for filtering in a generic way)

  • 12
    点赞
  • 49
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值