How to redefine both cerr and clog to both tee to a shared log file?

孤街浪徒 提交于 2020-01-16 21:35:26

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!