Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>So, I took a look at <a href="http://www.boost.org/doc/libs/1_41_0/index.html" rel="nofollow noreferrer">Boost.IOstreams</a> and here's what I've come up with:</p> <pre><code>class TestSink : public boost::iostreams::sink { public: std::streamsize write( const char * s, std::streamsize n ) { std::string message( s, n ); /* This would add a message to the log instead of cout. The log implementation is threadsafe. */ std::cout &lt;&lt; message &lt;&lt; std::endl; return n; } }; </code></pre> <p><code>TestSink</code> can be used to create a stream-buffer (see <a href="http://www.boost.org/doc/libs/1_41_0/libs/iostreams/doc/guide/generic_streams.html#stream_buffer" rel="nofollow noreferrer">stream_buffer-template</a>). Every thread will receive it's own instance of <code>TestSink</code>, but all <code>TestSinks</code> will write to the same log. <code>TestSink</code> is used as follows:</p> <pre><code>TestSink sink; boost::iostreams::stream_buffer&lt; TestSink &gt; testbuf( sink, 50000 ); std::ostream out( &amp;testbuf ); for ( int i = 0; i &lt; 10000; i++ ) out &lt;&lt; "test" &lt;&lt; i; out &lt;&lt; std::endl; </code></pre> <p>The important fact here is, that <code>TestSink.write</code> is only called when the stream is flushed (<code>std::endl</code> or <code>std::flush</code>), or when the internal buffer of the <code>stream_buffer</code> instance is full (the default buffer size cannot hold 40000 chars, so I initalize it to 50000). In this program, <code>TestSink.write</code> 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.</p> <p>I will leave the question open another day, in case there are different suggestions/problems I have not considered.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload