Empty space at beginning of rsyslog log file

4.2k views Asked by At

Using this rsyslog config:

$template MYFORMAT,"%msg%\n"

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

and this PHP script:

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

My output always ends up having an empty space before the logged message (in the custom log file).

 2015-06-10: stuff has happened! (there's a space at the beginning of this line)
4

There are 4 answers

0
Kevin Burke On

Per RFC 3164, anything after the colon in the syslog tag gets counted as part of the %msg% field, including any space character. This is alluded to in various rsyslog documentation/blog posts, for example https://www.rsyslog.com/log-normalization-and-the-leading-space/ or the sp-if-no-sp documentation here https://rsyslog.readthedocs.io/en/latest/configuration/property_replacer.html

Since it's part of the %msg% field, there are two ways to log lines without a leading space:

  • 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"
    
0
a lead alcove On

Yes, rsyslog is adding the space due it being in date('Y-m-d: ')

Remove the space after the colon like so:

Change

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

to

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

The php should look like this:

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

Modify that

$template MYFORMAT,"%msg%\n"

for

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

You can also use regex based property replacer as follows:

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

The statement above picks the 1st group (all chars after leading spaces) from MSG string matching the given regex (^[ \t]*(.*)$). Note that, the regex syntax is POSIX ERE (Extended Regular Expressions).