I created my own std::cout
-like object that writes both to std::cout
and to a log file.
I'm currently defining it like this in a header file, but I'm getting unused variable warnings.
Header file <MyLib/Log.h>
static LOut { };
static LOut lo;
template<typename T> inline LOut& operator<<(LOut& mLOut, const T& mValue)
{
std::string str{toStr(mValue)};
std::cout << str;
getLogStream() << str;
return mLOut;
}
Usage:
#include <MyLib/Log.h>
...
lo << "hello!" << std::endl;
Should lo
be static
? Should lo
be extern
?
Kudos for explaining the correct way of declaring a cout
-like object and showing how the main standard library implementations do it.
Edit: by cout
-like object, I mean a global variable that is always available after including the corresponding header.
In one of my projects, I wrote wrapper for
std::cout
.It looks something like this:
For complete code look for
struct out
inio.h
First, I'm not too sure what you mean be a
cout
-like object? Perhaps anstd::ostream
.Anyway, the usual way of doing this is to use a filtering streambuf. Just write a streambuf which forwards to a log file, in addition to the usual place, and insert it where ever you want:
(This is C++11, but it shouldn't be hard to modify it for C++03.)
To use, you could use something like:
All output to
std::cout
will be logged untillogger
goes out of scope.In practice, you'll likely use something more complicated than a
filebuf
for logging, since you may want to insert time stamps at the start of each line, or systematically flush at the end of each line. (Filtering streambufs can take care of those issues as well.)std::cout
is simply declared as follows:It is a regular global variable; you can do the same thing yourself. Put an
extern
declaration of your variable in a header; then define the same variable in a source file and link it to your application:Simply sending the input value right out to cout didn't work for me, because I wanted to add headers and info to the log output.
Also, I had my static Debug class in which to wrap the Log stream.
This is the way I managed to do this, I hope it's useful. I'm somehow a newbye to c++, so feel free to tell me if something is wrong :)
Maybe boost.iostreams would be sufficient?