general question is i like to build logger class that writes to single log file from different classes in my application what should the logger class be singletone or static class
What makes you think it should be either? What about a regular non-static class which can be instantiated on demand? And then make a single static instance of it available as the default logger. That way you get the best of both worlds: convenient global access to the logger and the ability to test it or temporarily use a different logger.
Another suggestion is to simply create a single instance and pass it as a parameter to every component of your class, as @disown suggests.
But if you make the class itself static or a singleton, you're just shooting yourself in the foot.
Edit
Example, in response to @Stephen's comment:
// define a logger class, a perfectly ordinary class, not a singleton, and without all static members
class Logger {
// ....
};
// create a single global *instance* of this class
Logger defaultLog;
void foo() {
// and now use the globally visible instance
defaultLog.Log("hello");
// or create a new one if that's what we need:
Logger newlog;
newlog.Log("hello");
}
There's no magic. This is exactly what the standard library does. std::cout
isn't a singleton. It is simply a global instance of class std::ostream
, a class which can also be instantiated normally if and when you need it.
In C++ you'll want a singleton rather than a static. C++ does not allow you to control the order static objects are constructed and destructed, and if you tried to log before the static was constructed behaviour would possibly be undefined.
I'm not sure about Java.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With