【问题标题】:rsyslog template "eating" the first part of a messagersyslog 模板“吃掉”消息的第一部分
【发布时间】:2016-07-01 21:23:50
【问题描述】:

我正在使用 Python 的 SysLogHandler 将消息记录到 syslog。问题是 startswith 与模板结合似乎“吃掉”了记录字符串的开头。

Rsyslogd 版本为 8.4.2,Python 2.7.9(在 2.7.11 上的行为相同)。然而,在带有 Python 2.7.4 的 rsyslogd 7.x 上似乎不会发生这种情况。

例子:

#!/usr/bin/env python
import logging
from logging.handlers import SysLogHandler

my_fmt = logging.Formatter('%(name)s:%(message)s', '%Y-%m-%d %H:%M:%S')
foo_handler = SysLogHandler(address='/dev/log', facility=SysLogHandler.LOG_LOCAL5)
foo_handler.setLevel(logging.INFO)
foo_handler.setFormatter(my_fmt)

foo = logging.getLogger('foo')
foo.setLevel(logging.INFO)
foo.addHandler(foo_handler)
foo.propagate = False

foo.info("This is foo")

使用此 rsyslog 配置:

$template myt,"%TIMESTAMP:::date-rfc3339%%msg:::sp-if-no-1st-sp%%msg:::drop-last-lf%\n"

if $syslogfacility-text == "local5" then {
    if $msg startswith "foo" then {
        action(type="omfile" file="/var/log/foo.log" template="myt")
    } else {
        action(type="omfile" file="/var/log/bar.log" template="myt")
    }
    stop
}

产生以下内容:

=> /var/log/bar.log <==
2016-06-29T17:29:55.330941+01:00 is foo

请注意消息中缺少的“This”。

相反,在 rsyslog 配置文件中删除使用模板会导致:

==> /var/log/bar.log <==
Jun 29 18:19:40 localhost foo:This is foo

从模板中删除 %msg:::sp-if-no-1st-sp% 似乎也没有帮助。

【问题讨论】:

    标签: python rsyslog


    【解决方案1】:

    解决方案似乎是:

    1. 使用$syslogtag startswith 代替$msg startswith
    2. 在 python 源代码中,分隔 name 与字符串的其余部分用空格分开:logging.Formatter('%(name)s: %(message)s', '%Y-%m-%d %H:%M:%S')

    我不确定为什么这在 2.7.4 上不是问题,如果有人找到原因,请在下面发表评论。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-08
      • 1970-01-01
      • 2018-06-02
      • 1970-01-01
      • 1970-01-01
      • 2010-09-07
      • 1970-01-01
      • 2016-12-12
      相关资源
      最近更新 更多