Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton, Logging and Global Settings - Good or Bad implementation?

I've got a logging class which requires need to be called from almost everywhere in the application.

However it requires setup in the beginning of the application with "which path to write", "log level" and if it's "enabled" or not.

I don't want to give this parameters every time or pass Logging class as parameter to every single object in my application, so I do use singleton pattern for logging.

Recently I've suffered a lot from tightly coupled classes I don't want to do the same mistake again but after thinking about this sounds like this is the only good solution.

UPDATE :

I don't really care about logging what I care is solving similar design issues, I'm having the same dilemma with another global settings object which requires to be used from so many classes. But injecting it into every single of them just makes a horrible overhead and less readable code.

What do you think about this implementation and what do you do when you come across similar design decisions?

P.S. Please do not suggest something like "use Log4X library" etc.

like image 659
dr. evil Avatar asked Apr 28 '09 07:04

dr. evil


1 Answers

First - could you write the log writer as a trace listener, and use Trace.Write etc from the methods?

Do you actually need an instance here? That would be useful, for example, if you wanted to abstract it as a TextWriter or similar - but if it is going to be a standalone singleton, can the methods not use static methods directly, i.e. Log.Write(...) (rather than passing in a log instance)?

Re the general problem - it depends on the types that are doing the logging. For "manager" (etc) classes, you might consider using dependency injection (Unity, StructureMap, etc) to automate this. I wouldn't normally use injection with DTOs, though.

like image 111
Marc Gravell Avatar answered Sep 28 '22 04:09

Marc Gravell