【问题标题】:How to redefine both cerr and clog to both tee to a shared log file?如何将 cerr 和 clog 重新定义为 tee 到共享日志文件?
【发布时间】:2011-05-30 16:00:38
【问题描述】:

此处的一个相关问题显示了如何仅使用 clog 来做到这一点:

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

现在的问题是如何同时为 cerr 执行此操作。对于上述问题,cerr 的输出不会出现在也需要它的日志文件中。

目标是任何进入 clog 或 cerr 的内容都会在日志文件中结束一次,因此 clog 和 cerr 都需要放到一个共享的日志文件中。

【问题讨论】:

标签: c++ logfiles tee clog


【解决方案1】:

此代码会将 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);

【讨论】:

  • 但是 cout 和 cerr 还会继续进入控制台吗?我想给这些发球台,而不仅仅是重定向它们。
猜你喜欢
  • 2010-10-30
  • 2023-04-07
  • 1970-01-01
  • 2012-11-01
  • 2011-01-25
  • 2014-05-03
  • 2010-09-22
  • 2012-03-09
相关资源
最近更新 更多