6

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)
Ian
  • 24,116
  • 22
  • 58
  • 96

4 Answers4

4

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"
    
Kevin Burke
  • 61,194
  • 76
  • 188
  • 305
2

Modify that

$template MYFORMAT,"%msg%\n"

for

$template MYFORMAT,"%msg:2:2048%\n"
rene
  • 41,474
  • 78
  • 114
  • 152
  • Why should it be modified like that? Maybe add some explanation, backed by documentation or so? Show what the different result will be? – rene Aug 05 '17 at 07:40
  • substring from position 2 to 2048. I like it. Works great, and fast. – Stickley May 30 '20 at 00:01
1

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).

ovunccetin
  • 8,443
  • 5
  • 42
  • 53
0

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();
a lead alcove
  • 305
  • 1
  • 14