I'm trying to find a decent way to do logging from C++. My current solution is this:
ostream & GetLog() { if( output == NULL ) throw error; return *output; }
Where output is defined somewhere and can be a file or whatever. This is fine, but it doesn't let me do anything other than throw an error if output is not allocated. Also, my program is multithreaded, and I need to obtain a lock in order to correctly check if output is not NULL and then write to it if it is not. Ideally, any code that uses GetLog() should obtain that lock:
{
LockLog lock;
if( HasLog() )
GetLog() << "My dog ate " << n << " cookies!" << endl;
}
This seems like too much verbiage to me. I'd like to do something like just
GetLog() << "My dog ate " << n << " cookies!" << endl;
and have it work without an error when the log's not allocated (and with lock), or a function like
WriteLog( "My dog ate " << n << " cookies!" << endl );
I know with C printf syntax this can be done with variable argument function. Is there a way to do this with C++ syntax and without a macro that would force me to expose the GetLog, HasLog, and LockLog functions anyway?