I want to implement a simple class for logging from multiple threads. The idea there is, that each object that wants to log stuff, receives an ostream-object that it can write messages to using the usual operators. The desired behaviour is, that the messages are added to the log when the stream is flushed. This way, messages will not get interrupted by messages from other threads. I want to avoid using a temporary stringstream to store the message, as that would make most messages at least twoliners. As I see it, the standard way of achieving this would be to implement my own streambuffer, but this seems very cumbersome and error-prone. Is there a simpler way to do this? If not, do you know a good article/howto/guide on custom streambufs?
Thanks in advance,
Space_C0wbo0y
UPDATE:
Since it seems to work I added my own answer.
So, I took a look at Boost.IOstreams and here's what I've come up with:
TestSink
can be used to create a stream-buffer (see stream_buffer-template). Every thread will receive it's own instance ofTestSink
, but allTestSinks
will write to the same log.TestSink
is used as follows:The important fact here is, that
TestSink.write
is only called when the stream is flushed (std::endl
orstd::flush
), or when the internal buffer of thestream_buffer
instance is full (the default buffer size cannot hold 40000 chars, so I initalize it to 50000). In this program,TestSink.write
is called exactly once (the output is too long to post here). This way I can write logmessage using normal formatted stream-IO without any temporary variables and be sure, that the message is posted to the log in one piece when I flush the stream.I will leave the question open another day, in case there are different suggestions/problems I have not considered.