Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper Logging in OOP context

Here is a problem I've struggled with ever since I first started learning object-oriented programming: how should one implement a logger in "proper" OOP code?

By this, I mean an object that has a method that we want every other object in the code to be able to access; this method would output to console/file/whatever, which we would use for logging--hence, this object would be the logger object.

We don't want to establish the logger object as a global variable, because global variables are bad, right? But we also don't want to have the pass the logger object in the parameters of every single method we call in every single object.

In college, when I brought this up to the professor, he couldn't actually give me an answer. I realize that there are actually packages (for say, Java) that might implement this functionality. What I am ultimately looking for, though, is the knowledge of how to properly and in the OOP way implement this myself.

like image 880
Kate Bertelsen Avatar asked Sep 17 '08 19:09

Kate Bertelsen


2 Answers

You do want to establish the logger as a global variable, because global variables are not bad. At least, they aren't inherently bad. A logger is a great example of the proper use of a globally accessible object. Read about the Singleton design pattern if you want more information.

like image 166
benzado Avatar answered Sep 17 '22 18:09

benzado


There are some very well thought out solutions. Some involve bypassing OO and using another mechanism (AOP).

Logging doesn't really lend itself too well to OO (which is okay, not everything does). If you have to implement it yourself, I suggest just instantiating "Log" at the top of each class:

private final log=new Log(this);

and all your logging calls are then trivial: log.print("Hey");

Which makes it much easier to use than a singleton.

Have your logger figure out what class you are passing in and use that to annotate the log. Since you then have an instance of log, you can then do things like:

log.addTag("Bill");

And log can add the tag bill to each entry so that you can implement better filtering for your display.

log4j and chainsaw are a perfect out of the box solution though--if you aren't just being academic, use those.

like image 33
Bill K Avatar answered Sep 20 '22 18:09

Bill K