【问题标题】:How to redefine clog's rdbuf() to be a tee to the original rdbuf() of clog and that of a log file?如何将 clog 的 rdbuf() 重新定义为 clog 的原始 rdbuf() 和日志文件的 tee?
【发布时间】:2010-10-30 20:30:43
【问题描述】:

有没有人有一个例子来说明如何重新定义 C++ 内置 clog 来代替有一个新的关联 rdbuf(),它被处理为原始 clog.rdbuf() 的 tee 和 ofstream 对象的 rdbuf()到磁盘上的日志文件。

目的是让代码始终使用std::clog,但让它同时进入默认的clog目标以及磁盘上的日志文件。

谢谢。

-威廉

【问题讨论】:

标签: c++ stream tee clog


【解决方案1】:

您必须编写一个自定义的 streambuf 派生类。让它向你的 ofstream 的 rdbuf 和你原来的阻塞 rdbuf 吐出数据。

编写自定义streambuf的一般示例:

http://www.dreamincode.net/code/snippet2499.htm

可以按如下方式存储新的流缓冲区:

// grab buffer for clog
std::streambuf* oldClogBuf = std::clog.rdbuf();

// create custom buffer which feeds both clog and an ofstream
CustomBuffer* customBuf = new CustomBuffer( oldClogBuf );

// stash custom buffer
std::clog.rdbuf( customBuf );

...do stuff...

// restore original clog buffer
std::clog.rdbuf( oldClogBuf );

您可以通过使用 RAII 习惯用法来管理缓冲区切换,从而使整个事情变得更加健壮。

【讨论】:

    猜你喜欢
    • 2023-04-07
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2011-02-07
    • 1970-01-01
    • 2011-01-25
    相关资源
    最近更新 更多