【发布时间】: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% 似乎也没有帮助。
【问题讨论】: