First, I'm not too sure what you mean by a cout -like object? Maybe std::ostream .
In any case, the usual way to do this is to use streambuf filtering. Just write streambuf, which sends it to the log file, in addition to the usual place, and paste it wherever you want:
class LoggingOutputStreambuf : public std::streambuf { std::streambuf* myDest; std::ofstreambuf myLogFile; std::ostream* myOwner; protected: int overflow( int ch ) { myLogFile.sputc( ch );
(This is C ++ 11, but it should not be changed for C ++ 03).
To use, you can use something like:
LoggingOutputStreambuf logger( std::cout );
All output from std::cout will be logged until the logger goes out of scope.
In practice, you'll probably use something more complex than filebuf for logging, as you can insert timestamps at the beginning of each line or systematically flush each line at the end. (Filtering streambufs can take care of these issues as well.)
source share