rsyslog日志文件开头的空白空间

6
使用以下rsyslog配置:
$template MYFORMAT,"%msg%\n"

if $programname == 'mylog' then {
        action(type="omfile" file="/var/log/mylog.log" template="MYFORMAT")
        & stop
}

以及这段 PHP 脚本:

<?php
    openlog('mylog', LOG_ODELAY, LOG_LOCAL0);
    syslog(LOG_INFO, date('Y-m-d: ') . 'stuff has happened!');
    closelog();

我的输出总是在记录的消息(在自定义日志文件中)之前有一个空格。
 2015-06-10: stuff has happened! (there's a space at the beginning of this line)
4个回答

4
根据RFC 3164的规定,syslog标记中冒号后面的所有内容都会被计算为%msg%字段的一部分,包括任何空格字符。rsyslog文档/博客文章中都提到了这一点,例如https://www.rsyslog.com/log-normalization-and-the-leading-space/或此处的sp-if-no-sp文档https://rsyslog.readthedocs.io/en/latest/configuration/property_replacer.html 由于它是%msg%字段的一部分,因此有两种方法可以记录没有前导空格的行:
  • Hard code a prefix as part of every log line, for example:

    $template MYFORMAT,"[app]: %msg%\n"
    
  • Strip the leading space character. You can use a $ sign to say "include everything until the end of the line." The msg characters are 1-indexed, so start with field 2.

    $template MYFORMAT,"%msg:2:$%\n"
    

2

修改那个

$template MYFORMAT,"%msg%\n"

对于

$template MYFORMAT,"%msg:2:2048%\n"

为什么要这样修改?可以加上一些解释,支持文档或其他证明吗?展示不同的结果会是什么样子? - rene
从位置2到2048提取子字符串。我喜欢它。工作得很好,而且速度很快。 - Stickley

1
你也可以使用基于正则表达式的属性替换器,如下所示:
template(name="logfmt" type="string" string="%msg:R,ERE,1,FIELD:^[ \t]*(.*)$--end%\n")

上面的语句从匹配给定正则表达式(^[ \t]*(.*)$)的MSG字符串中选取第1组(所有前导空格后的所有字符)。请注意,正则表达式语法是POSIX ERE(扩展正则表达式)。

0

是的,rsyslog会添加空格,因为它在date('Y-m-d: ')中。

像这样删除冒号后面的空格:

更改

"syslog(LOG_INFO, date('Y-m-d: ') . 'stuff has happened!');" 

syslog(LOG_INFO, date('Y-m-d:') . 'stuff has happened!');"

PHP代码应该长这样:

<?php
    openlog('mylog', LOG_ODELAY, LOG_LOCAL0);
    syslog(LOG_INFO, date('Y-m-d:') . 'stuff has happened!');
    closelog();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接