I have the following code which is redirecting my std::cout
output to a log file.
std::ofstream out("out.txt");
std::streambuf *coutbuf = std::cout.rdbuf(); //save old buf
std::cout.rdbuf(out.rdbuf()); //redirect std::cout to out.txt!
Now what I want is that whenever a newline is occurring, then the current time stamp will be written to the file.
I know I can achive this with:
std::cout << getTime() << "printing data" << std::endl;
But what I want is that of std::cout
taking care of it automatically somehow. Is that possible?
That's a hack from a different point.
When you run the program, pipe the output into awk, and add there the time stamp. The command:
If you are using windows, you can download gawk from this website.
You can format the time printed by
strftime
. More data on that can be found in the manualtry something like the following (it's just an abstract, I didn't test it):
You want something like:
and use it like this:
I assume, that You want print the TimeStamp, if the first character of the next line appears in the output. Take a new class and inherit it from std::streambuf and connect it in the same way You do with the filebuf. If a newline-charater appears store this event in the object. Appears another character add the timestamp to the stream.
I wrote an example which use the RAII idiom for connecting the streambuf.
call an object of this class in following way: