rsyslog日志文件开头为空


Empty space at beginning of rsyslog log file

使用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)

根据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%字段的一部分,所以有两种不带前导空格的方式记录行:

  • 硬编码前缀作为每个日志行的一部分,例如:

    $template MYFORMAT,"[app]: %msg%'n"
    
  • 去掉前导空格字符。您可以使用$符号表示"包括行尾之前的所有内容"。msg字符是以1为索引的,所以从字段2开始。

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

修改

$template MYFORMAT,"%msg%'n"

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

您还可以使用基于regex的属性替换器,如下所示:

template(name="logfmt" type="string" string="%msg:R,ERE,1,FIELD:^[ 't]*(.*)$--end%'n")

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

是,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();