Empty space at beginning of rsyslog log file
Asked Answered
B

4

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)
Bumbling answered 10/6, 2015 at 0:35 Comment(0)
H
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"
    
Hasseman answered 16/7, 2020 at 17:12 Comment(0)
B
2

Modify that

$template MYFORMAT,"%msg%\n"

for

$template MYFORMAT,"%msg:2:2048%\n"
Brietta answered 5/8, 2017 at 6:54 Comment(2)
Why should it be modified like that? Maybe add some explanation, backed by documentation or so? Show what the different result will be?Tacmahack
substring from position 2 to 2048. I like it. Works great, and fast.Hollenbeck
M
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).

Middlemost answered 24/6, 2019 at 7:41 Comment(0)
V
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();
Vocable answered 23/7, 2020 at 6:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.