Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional logging in python

Tags:

python

logging

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!

like image 438
zenzic Avatar asked Nov 05 '22 16:11

zenzic


1 Answers

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.

like image 168
cwallenpoole Avatar answered Nov 09 '22 05:11

cwallenpoole