问题
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.
回答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);
来源:https://stackoverflow.com/questions/4530751/how-to-redefine-both-cerr-and-clog-to-both-tee-to-a-shared-log-file