如何使用rsyslog和imfile

时间:2017-02-15 15:34:38

标签: rsyslog

美好的一天

我想使用imfile文件输入模块将文本文件导入rsyslog。但是,rsyslog没有像我预期的那样解析文本文件的内容,而且我正在努力寻找关于它是如何完成的文档。为了测试设置,我正在使用imfile读取文本文件,然后使用omfile将日志写入另一个文本文件。

文本文件的内容是“标准”系统日志格式的日志:

<PRI>TIMESTAMP HOSTNAME MESSAGE

我要导入Rsyslog的示例文本文件(example_file.txt。)如下所示:

<34>Feb 15 12:12:12 hostname1 tag1: message1
<34>Feb 16 12:12:12 hostname2 tag2: message2
<34>Feb 17 12:12:12 hostname3 tag3: message3

rsyslog-d中rsyslog的配置文件如下所示:

module(load = "imfile")
input(type = "imfile" file = "/home/.../Desktop/example_file.txt" Tag = "example")
action(type = "omfile" file = "/home/.../Desktop/example_output.log")

example_output.log中的结果输出如下所示:

Feb 15 17:10:21 username example <34>Feb 15 12:12:12 hostname1 tag1: message1
Feb 15 17:10:21 username example <34>Feb 16 12:12:12 hostname1 tag2: message2
Feb 15 17:10:21 username example <34>Feb 17 12:12:12 hostname1 tag3: message3

如您所见,example_file.txt中的所有内容都放在example_output.log中生成的日志的MSG字段中,而不是使用字段信息并将它们放在正确的位置,例如TIMESTAMP,HOSTNAME,TAG,MSG。我在.txt文件中使用了不同的格式,甚至将.txt文件保存为.log文件,但rsyslog每次都将整个内容放在MSG字段中。

我的问题是:

如何告诉rsyslog和imfile我的.txt内容实际上是日志并正确解析它们?

考虑到:

  1. 我正在使用Linux v4.4.0-ubi4-amd64(UbiLinux)进行Up-Board

  2. 我使用的是rsyslog8.24(最新稳定版)

  3. 我已经通读了:

    -Rsyslog官方文档,

    -Imfile官方文档,

    -Rainer Gerhards在rsyslog中解析syslog(http://www.rsyslog.com/doc/syslog_parsing.html),

    - 甚至是BSD Syslog协议RFC3164(http://www.ietf.org/rfc/rfc3164.txt)的文档

2 个答案:

答案 0 :(得分:0)

您可以使用templates从消息中提取字段。这是一个示例模板。

template(name="structured-format" type="list") {
   constant(value="{")
       property(outname="pri" name="msg" field.number="1" field.delimiter="32" format="jsonf") 
       constant(value=", ")
       property(outname="hostname" name="msg" field.number="4" field.delimiter="32" format="jsonf") 
       constant(value=", ")
       property(name="msg" format="jsonf")
   constant(value="} \n")
}

您可以像这样在输出中使用此模板。

action(type = "omfile" file = "/home/.../Desktop/example_output.log" template="structured-format") 

输出看起来像这样:

{"pri":"<34>", "hostname":"hostname1", "msg":"<34>Feb 15 12:12:12 hostname1 tag1: message1"}

也就是说,我还没有弄清楚如何从msg中排除已解析的字段,而仅将其余字段添加到msg字段中。希望对您有所帮助。

答案 1 :(得分:0)

如何告诉 rsyslog 和 imfile 我的 .txt 内容实际上是日志并正确解析它们?

这可以使用如下模板来完成(使用以下规则更新 rsyslog.conf)

#Define a template of type string which just formats output to be send
#                  to remote as line read from file. Named "tpl1" here.

template(name="tpl1" type="string"
     string="%msg:::sp-if-no-1st-sp%%msg:::drop-last-lf%\n"
    )


#Load imfile module to read file with log messages
#Specify the input (which file to read) and action (where to send log messages 
#along with template to be used)

module(load="imfile")
input(type="imfile" file="/var/log/FileWithLogMessages.log" Tag="GiveSomeTag")
action(type="omfwd" target="192.168.0.1" Port="514" Protocol="udp" 
template="tpl1")

参考:

模板 :https://rsyslog.readthedocs.io/en/latest/configuration/templates.html