I want to include logging in a module, but I don't want the module to create a new log object/file, I want it to use the callers log object, whatever that may be, but only if they pass one. I know I could put all my log calls in a try block, but that's awkward. What I finally came up with seems to work, but it seems pretty kludgy and I'm sure there's a better way to do it.
class MyClass(object):
def __init__(self, arg1, arg2, log=None):
if log == None:
class log(object):
def error(self, msg): pass
def warning(self, msg): pass
def info(self, msg): pass
def debug(self, msg): pass
self.log = log()
else:
self.log = log
self.log.debug('Starting')
What's a better way to do something like this?
Thanks!
Most loggers use the factory pattern to let some centralized resource manage which classes (if any) get loggers which actually log (instead of calling dummy functions). This means that there is a centralized API, centralized control, and there becomes no need to have loggers defined on a class-by-class basis.
It is generally a good idea to view passed parameters as a signal from one thing to another, "You need to use this object to do your job." Unless MyClass
is a logger, it doesn't really make sense to pass it one as a parameter -- it shouldn't need a logger to do its job, if it does that is bad design.
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