Search code examples
cloggingsyslog

writing type of error in log file with syslog (linux)


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)


Solution

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