开发者

Internal "Tee" setup

开发者 https://www.devze.com 2023-01-03 05:23 出处:网络
I have inherited some really old VC6.0 code that I am upgrading to VS2008 for building a 64-bit app.One required feature that was implemented long, long ago is overriding std::cout so its output goes

I have inherited some really old VC6.0 code that I am upgrading to VS2008 for building a 64-bit app. One required feature that was implemented long, long ago is overriding std::cout so its output goes simult开发者_如何学编程aneously to a console window and to a file. The implementation depended on the then-current VC98 library implementation of ostream and, of course, is now irretrievably broken with VS2008. It would be reasonable to accumulate all the output until program termination time and then dump it to a file. I got part of the way home by using freopen(), setvbuf(), and ios::sync_with_stdio(), but to my dismay, the internal library does not treat its buffer as a ring buffer; instead when it flushes to the output device it restarts at the beginning, so every flush wipes out all my accumulated output. Converting to a more standard logging function is not desirable, as there are over 1600 usages of "std::cout << " scattered throughout almost 60 files. I have considered overriding ostream's operator<< function, but I'm not sure if that will cover me, since there are global operator<< functions that can't be overridden. (Or can they?)

Any ideas on how to accomplish this?


You could write a custom stream buffer and attach it to cout with cout.rdbuf(). Your custom stream buffer would then tee the data to cout's original stream buffer and to a stream buffer stolen from an appropriate ofstream.

ofstream flog("log.txt");
teebuf tb(flog.rdbuf(), cout.rdbuf());
cout.rdbuf(&tb);

For your teeing stream buffer you can get an inspiration from this page.


You could use the pre-processor:

#define cout MyLogger

to inject new code.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号