10

I have an application that can run in two modes, either with a CLI, or as a daemon.

I am using syslog() for logging. However, when run in CLI mode I'd like all the logging, except those marked LOG_DEBUG, messages to be sent to the console instead of logged.

I have tried to use setlogmask(), but that doesn't seem to redirect to console.

What is the best way to do this?

Kevin Panko
  • 8,356
  • 19
  • 50
  • 61
Brandon Yates
  • 2,022
  • 3
  • 22
  • 33
  • 2
    AFAIK, FreeBSD's syslog allows redirecting through /etc/syslog.conf. Anyway, it is not a way you're looking for. I suggest to write function that will detects if you're running as CLI app or daemon and does what it should: write to console or to syslog. – maverik May 08 '13 at 16:58

2 Answers2

4

As suggested in the comments by maverik, I wrote a wrapper around syslog that determines whether to send the output to the log or console. Here it is in case anyone ever needs this.

void mylog (int level, const char *format, ...)
{
    va_list args;
    va_start (args, format);

    if (remote)
    {
        vsyslog(level, format, args);
    }   
    else
    {
        if (level == LOG_DEBUG)
            vsyslog(level, format, args);
        else
            vprintf(format, args);
    }
    va_end(args);
}
Jens
  • 69,818
  • 15
  • 125
  • 179
Brandon Yates
  • 2,022
  • 3
  • 22
  • 33
4

As GNU-specific solution I would suggest using openlog(NULL, LOG_PERROR, your_facility). Not customizable(just duplicate on stderr).

KAction
  • 1,977
  • 15
  • 31