Reputation: 948
have a question about using syslog library in writing the error messages to the log file.
Below is the code function I am trying to use
syslog(int priority, const char_message)
and I want to print priority of massage in the log file. for example:
Mar 23 17:56:37 mypc slog[3597]: this is log massage "ERR"
but now it is only shows:
Mar 23 17:56:37 mypc slog[3597]: this is log massage
is there anyway i can write to the log file the type of priority too? (syslog accept only string literal)
Upvotes: 1
Views: 2021
Reputation: 2329
Note that the syslog message already contains the priority but it is stripped by the syslog daemon (e.g. rsyslog) when it is written into the file. The syslog message that is passed by the syslog()
call to the syslog daemon actually looks like this:
<16>Mar 23 17:56:37 mypc slog[3597]: this is log massage
It is possible to reconfigure the syslog daemon so that the priority is also printed. Rsyslog uses templates and with NXLog you could simply do this:
Exec $raw_event = $raw_evnt + " " + $SyslogSeverity;
See also https://stackoverflow.com/a/9216977/995934
Upvotes: 0
Reputation: 17403
The function prototype of syslog
is:
void syslog(int priority, const char *format, ...);
In particular, the second parameter is similar to a printf
-style format specifier except that is also supports the specifier %m
which will be replaced with an error message generated by strerror(errno)
.
You could log a simple string along with a priority string by calling this function:
void my_simple_syslog(int priority, const char *message)
{
static const char * const prio_strings[] = {
[LOG_EMERG] = "EMERG",
[LOG_ALERT] = "ALERT",
[LOG_CRIT] = "CRIT",
[LOG_ERR] = "ERR",
[LOG_WARNING] = "WARNING",
[LOG_NOTICE] = "NOTICE",
[LOG_INFO] = "INFO",
[LOG_DEBUG] = "DEBUG",
};
if (priority < 0 ||
priority >= sizeof(prio_strings) / sizeof(prio_strings[0]) ||
!prio_strings[priority]) {
/* priority is an unknown value */
syslog(priority, "%s [PRIORITY:%d]", message, priority);
} else {
syslog(priority, "%s [%s]", message, prio_strings[priority]);
}
}
This example call:
my_simple_syslog(LOG_ERR, "this is log massage");
produces a log message similar to:
Mar 23 17:56:37 mypc slog[3597]: this is log massage [ERR]
The downside with using this canned approach is that you cannot add extra parameters like you could with calling syslog
directly.
Upvotes: 1