所以,我看了一下Boost.IOstreams,这是我想出的:
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 << message << std::endl;
return n;
}
};
TestSink
可用于创建流缓冲区(请参阅stream_buffer-template)。每个线程都会收到它自己的实例TestSink
,但都TestSinks
将写入同一个日志。TestSink
使用如下:
TestSink sink;
boost::iostreams::stream_buffer< TestSink > testbuf( sink, 50000 );
std::ostream out( &testbuf );
for ( int i = 0; i < 10000; i++ )
out << "test" << i;
out << std::endl;
这里的重要事实是,它TestSink.write
仅在流被刷新(std::endl
或std::flush
)时调用,或者当stream_buffer
实例的内部缓冲区已满时(默认缓冲区大小不能容纳 40000 个字符,因此我将其初始化为 50000)。在这个程序中,TestSink.write
只调用一次(输出太长,无法在此处发布)。这样,我可以使用普通格式的流 IO 编写日志消息,而无需任何临时变量,并确保在刷新流时将消息一次性发布到日志中。
如果有我没有考虑过的不同建议/问题,我将在另一天留下这个问题。