I\'m creating my own logging utility for my project, I want to create a function like iostream\'s std::cout, to log to a file and print to the console as well.
Here\
The trick is for your LOG(level)
to return a special type which
contains a pointer to an std::ostream
, and defines the <<
operator.
Something like:
class LogStream
{
std::ostream* myDest;
public:
LogStream( std::ostream* dest ) : myDest( dest ) {}
template
LogStream& operator<<( T const& obj )
{
if ( myDest != nullptr ) {
*myDest << obj;
}
return *this;
}
};
The LOG(level)
macro creats an instance of one, something like:
#define LOG(level) LogStream( getLogStream( level, __FILE__, __LINE__ ) )
Of course, the getLogStream
may insert any information it wants (like a timestamp) at the moment it is called.
You might want to add a flush in the destructor of LogStream
.