views:

459

answers:

2

I work on Unix on a C++ program that send messages to syslog.

The current code uses the syslog system call that works like printf.

Now I would prefer to use a stream for that purpose instead, typically the built-in std::clog. But clog merely redirect output to stderr, not to syslog and that is useless for me as I also use stderr and stdout for other purposes.

I've seen in another answer that it's quite easy to redirect it to a file using rdbuf() but I see no way to apply that method to call syslog as openlog does not return a file handler I could use to tie a stream on it.

Is there another method to do that ? (looks pretty basic for unix programming) ?

Edit: I'm looking for a solution that does not use external library. What @Chris is proposing could be a good start but is still a bit vague to become the accepted answer.

Edit: using Boost.IOStreams is OK as my project already use Boost anyway.

Linking with external library is possible but is also a concern as it's GPL code. Dependencies are also a burden as they may conflict with other components, not be available on my Linux distribution, introduce third-party bugs, etc. If this is the only solution I may consider completely avoiding streams... (a pity).

A: 

Look at using log4cpp or similar one of its appenders writes to syslog

Example code in example article shows how to use the logger as a stream

Mark
+8  A: 

You could define an streambuf that calls syslog. For example:

// Pseudo-code
class syslog_streambuf : public streambuf { 
private: 
    void internal_log(string& log) { 
        syslog(..., log, ...); 
    }
public: 
    int sputc ( char c ) { 
        internal_log(...); 
    }
    streamsize sputn ( const char * s, streamsize n ) { 
        internal_log(...); 
    } 
}

then you would simply write the following to redirect clog:

clog.rdbuf( new syslog_streambuf ); 

There are a few more functions you would probably have to override, here's a good reference to the streambuf api.

Chris Kaminski
Working example here: http://pastebin.org/184922
Basilevs
I think it's a good practice to create a separate ostream object for this specific task. Beware http://www.cplusplus.com/reference/iostream/ios_base/sync_with_stdio/ .
Basilevs
@Basilevs: thank for the sample. It's still short and it's definitely the kind of thing I was looking for. Anyway I will have to sort out the socket specific stuff to adapt the code for syslog... looks like it will take me at least a couple of days :-(
kriss