这里的一个相关问题展示了如何使用clog来做到这一点:
How to redefine clog to tee to original clog and a log file?
现在的问题是如何同时为cerr做这件事。对于上面的问题,到cerr的输出不会在日志文件中结束,因为日志文件也需要它。
我们的目标是,无论是发送到clog还是cerr的任何内容都会在日志文件中保存一次,因此需要将clog和cerr都绑定到一个共享日志文件中。
发布于 2010-12-26 07:02:56
此代码将把std::cout和std::cerr重定向到输出文件:
// 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
复制相似问题