Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if i want to build logger class in c++ or java what should it be singletone or static

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

like image 992
user63898 Avatar asked Jan 23 '23 08:01

user63898


2 Answers

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.

like image 54
jalf Avatar answered Feb 04 '23 17:02

jalf


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.

like image 43
Stephen Nutt Avatar answered Feb 04 '23 17:02

Stephen Nutt