【问题标题】:Empty space at beginning of rsyslog log filersyslog 日志文件开头的空白空间
【发布时间】:2015-08-25 01:05:44
【问题描述】:

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

【问题讨论】:

    标签: php linux logging rsyslog


    【解决方案1】:

    修改一下

    $template MYFORMAT,"%msg%\n"
    

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

    【讨论】:

    • 为什么要这样修改?也许添加一些解释,由文档支持?显示不同的结果会是什么?
    • 从位置 2 到 2048 的子字符串。我喜欢它。效果很好,速度很快。
    【解决方案2】:

    根据 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"
      

    【讨论】:

      【解决方案3】:

      您还可以使用基于正则表达式的属性替换器,如下所示:

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

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

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          猜你喜欢
          • 2021-02-28
          • 1970-01-01
          • 1970-01-01
          • 2012-09-17
          • 1970-01-01
          • 1970-01-01
          • 2014-06-17
          • 2023-03-17
          • 1970-01-01
          相关资源
          最近更新 更多