How to redefine clog's rdbuf() to be a tee to the original rdbuf() of clog and that of a log file?

StackOverflow https://stackoverflow.com/questions/942399

  •  09-09-2019
  •  | 
  •  

Question

Does anyone have an example of how to redefine the C++ built in clog to instead have a new associated rdbuf() which is processed to be a tee to the original clog.rdbuf() and the rdbuf() of a ofstream object to a log file on disk.

The intention is to have the code use the std::clog throughout but to have it go to the both the default clog destination as well as to a log file on disk.

Thanks.

-William

Was it helpful?

Solution

You will have to write a custom streambuf derived class. Have it spit out data to to both your ofstream's rdbuf and your original clog rdbuf.

A general example of writing a custom streambuf:

http://www.dreamincode.net/code/snippet2499.htm

Stashing the new stream buffer can be done as follows:

// grab buffer for clog
std::streambuf* oldClogBuf = std::clog.rdbuf();

// create custom buffer which feeds both clog and an ofstream
CustomBuffer* customBuf = new CustomBuffer( oldClogBuf );

// stash custom buffer
std::clog.rdbuf( customBuf );

...do stuff...

// restore original clog buffer
std::clog.rdbuf( oldClogBuf );

You can make the whole thing more robust by using the RAII idiom to manage the buffer switching.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top