Hi Paulo,
Using the Singleton Pattern is a good idea, and provides a centralised
point of control over the logging. One way to control the type of
logging is to provide different derived classes implementing the
logging in different ways, including a class that does no logging (
i.e. different logging Strategies ).
class Logging
{
public:
static Logging& instance()
{ if ( 0 == Logging::singleton )
{ if ( LOGGING_TYPE == COUT_LOGGING )
{ Logging::singleton = new CoutLogging();
}
else if ( LOGGING_TYPE == FILE_LOGGING )
{ Logging::singleton = new FileLogging();
}
// etc...
else
{ Logging::singleton = new NoLogging();
}
}
return *Logging::singleton;
}
public:
virtual Logging& loggingInterfaceMethods() = 0;
protected:
Logging();
private:
Logging( const Logging& );
Logging& operator=( const Logging& );
private:
static Logging* singleton;
};
class NoLogging : public Logging
{
public:
virtual Logging& loggingInterfaceMethods() { /* NOOP */ }
};
// etc ...
The selecting value LOGGING_TYPE could either be a #define in source
or in the make file / project settings for compile time selection, or
you could make it a dynamic property of the Logger to allow the
logging to vary at runtime after resetting the Logging class.
If your application peformance really is sensitive to even the ( 0 ==
Logging::singleton ) test ( which you can't avoid for this style of
Singleton Idiom in C++ ), then its worth considering if you really
need ( or even can afford ) to log the performance critical section of
code.
A possible alternative to the Singleton Pattern would be to use
Template Meta Programming techniques whereby the Logging Strategy
becomes a Policy template and the compiler can be used to ensure that
NoLogging Policy never generates any code at all ( similiar effect to
using MACROs, but far superior ). I'll refer you to the Modern C++
Design book if you're keen to learn those ideas.
You can in principle combine the two ideas, but now we're diverging
away from the quick and simple...
IMHO, I think the log4cpp library is excellent, and a good place to
start if looking for ideas (
http://log4cpp.sourceforge.net/ )
Regards,
Dieter Beaven