0

A related question here shows how to do this with just clog:

How to redefine clog to tee to original clog and a log file?

The question now is how to also do this for cerr at the same time. With the above question, output to cerr does not end up in the log file where it is also needed.

The goal is that whatever goes to either clog or cerr ends up in the log file once, so both clog and cerr need to be teed to a shared log file.

Community
  • 1
  • 1
WilliamKF
  • 41,123
  • 68
  • 193
  • 295
  • Just use an existing logger framework that takes care of these things in configuration/runtime. No need to implement this stuff yourself. http://logging.apache.org/log4cxx/index.html – Assaf Lavie Dec 25 '10 at 16:27

1 Answers1

1

this code will redirect both std::cout and std::cerr to an output file :

// create an output stream
std::ofstream trace_log ( "/tmp/foo.log" );

// connect stream buffers
std::streambuf *coutbuf = std::cout.rdbuf();
std::cout.rdbuf(trace_log.rdbuf () );

std::streambuf *cerrbuf = std::cerr.rdbuf();
std::cerr.rdbuf(trace_log.rdbuf () );

// log 
std::cout << "cout here" << std::endl;
std::cerr << "cerr here" << std::endl;

// restore
std::cout.flush ();
std::cout.rdbuf(cerrbuf);

std::cerr.flush ();
std::cerr.rdbuf(cerrbuf);
Javier Loureiro
  • 354
  • 2
  • 12
  • 1
    But will cout and cerr continue to also go to the console? I want to tee these, not just redirect them. – WilliamKF Dec 26 '10 at 16:53