0

I use rsyslog and want to log some actions from my application. The logging works fine and the log file will be created properly.

I formatted the output because I would like to see the programname:

rsyslog.conf:

$template usermsg,"%TIMESTAMP% %HOSTNAME% %programname% \n"
$ActionFileDefaultTemplate usermsg

Output:

Oct 14 16:28:25 box #001

I always get #001 as programname, although it should be "calculator". Does anybody have any idea how to fix that?

I create an instance of the logger in my application:

//ident = "calculator"

//facility= LOG_USER /* (1<<3) random user-level messages */

openlog(ident.c_str(), 0, facility);

Community
  • 1
  • 1
MeJ
  • 1,088
  • 10
  • 18

1 Answers1

1

At a wild guess, ident is a C++ string object of limited scope - i.e. it is most likely a local variable and the c_str() is, at best, a temporarily valid pointer.

This pointer has to remain valid for the entirety of the run of your application; openlog makes this clear in the manual:

The argument ident in the call of openlog() is probably stored as-is. Thus, if the string it points to is changed, syslog() may start prepending the changed string, and if the string it points to ceases to exist, the results are undefined. Most portable is to use a string constant.

The gnu.org manpage mentions:

Please note that the string pointer ident will be retained internally by the Syslog routines. You must not free the memory that ident points to. It is also dangerous to pass a reference to an automatic variable since leaving the scope would mean ending the lifetime of the variable. If you want to change the ident string, you must call openlog again; overwriting the string pointed to by ident is not thread-safe.

So the most likely thing is that the string variable is going out of scope, and you end up with a pointer to some random string, which in your case happens to be #001.

Solutions are many, but they all involve making sure that the data being pointed to by the c_str() don't change during the run of your application.

Anya Shenanigans
  • 91,618
  • 3
  • 107
  • 122