1

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

WilliamKF
  • 41,123
  • 68
  • 193
  • 295
  • Please do NOT ask the same question twice: http://stackoverflow.com/questions/937805/how-to-redefine-clog-to-tee-to-original-clog-and-a-log-file – lothar Jun 02 '09 at 23:32

1 Answers1

2

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.

nsanders
  • 12,250
  • 2
  • 40
  • 47