PDA

View Full Version : Logging using streams.


xconspirisist
08-20-2010, 12:31 AM
Hey folks, I've been picking up C++ over the last couple of days and most of my experience from other languages has transferred quite well. However, I'm trying to knock up a simple logging class and it's driving me nuts. I imagine this is quite a common request, but I can only pick up bits and bobs from around the net that don't seem to fully work.

I'd just like an abstract class with a bunch of stream's, so I could effectively do this;


Logger::err << "Hello " << 1 << 2;
Logger::norm << "Goodbye " << 3 << 4;


Then, I'd like to override some sort of onWrite method, that gives me the final strings "Hello 12" and "Goodbye 34", so I can do whatever I want with the final string. I've heard people talking about overloading the << operator, but that only lets me handle each argument one at a time and I don't really want to do that.

I know it's quite a lot to ask, but could someone post a code example that would work? Again, I've found bits and bobs, but this thing is driving me nuts!

Many thanks in advance for anyone who helps out.

ghell
08-22-2010, 06:42 PM
Personally I can't stand such C++ streams and prefer to use "printf" style format strings (but be aware of the security implications of these).

However, you could just look at the standard class "ostream" (of which cout, cerr etc are instances). http://www.cplusplus.com/reference/iostream/ostream/operator%3C%3C/

It seems to me your question really is just how to override the << operator in such a way that you can use left/right association as a syntactic sugar (in the same way that you can use a = b = c = 1, even though = is a binary operator)



I'd just use clog or some other ostream and use the rdbuf method from ios to make it output to a file instead.

http://www.cplusplus.com/reference/iostream/ios/rdbuf/