On Sat, 25 Aug 2007, [email protected] wrote:
Can anyone suggest the best way to pass a Logger object around between
all the classes in an application?
Currently I have it set in a constant in the top-level but I don’t
feel that this is the best way to do it as it couples the code in each
of my classes to the current implementation and makes it difficult for
me to reuse the code elsewhere without first setting up a logger
instance of the same name.
One approach is the way you are doing it. Just stuff your logger object
into ::Logger or some other constant, and have all of your code access
If you only have a few specific methods that need logging, and your app
structure allows it, you could have your app create a logger object that
it explicitly passes to the classes that can do logging. If you aren’t
going to be using the logging facilities when you reuse the code
elsewhere, then you just pass a dummy logger to your methods.
You could create a more sophisticated union of those ideas, too. Create
MyApp::Logger class that, by default, just provides dummy logging
facilities which just throw away the log messages. Provide a way that
dummy facilites can be overridden or initialized with a real logging
Then write all of you code to require this class, and to use it for
Apps that use the code without needing the logging will work, because
default behavior is to just throw the logs away. Apps that need the
can provide a real logging destination to your logger, though,
This is essentially how I do it in the IOWA web development framework.
There are a number of different logger classes which all adhere to the
same API. The app developer can select the logger that they want to
or provide their own, so long as it ahderes to the API, and all logging
for the application will just work, regardless of what the actual
If you need fast and flexible logging, you might also take a look at
If provides a very fast, simple asynchronous logging service that might
useful to you.