Naming Python loggers

后端 未结 3 570
深忆病人
深忆病人 2020-11-30 20:20

In Django, I\'ve got loggers all over the place, currently with hard-coded names.

For module-level logging (i.e., in a module of view functions) I have the urge to d

3条回答
  •  臣服心动
    2020-11-30 20:30

    For class level logging, as an alternative to a pseudo-class decorator, you could use a metaclass to make the logger for you at class creation time...

    import logging
    
    class Foo(object):
        class __metaclass__(type):
            def __init__(cls, name, bases, attrs):
                type.__init__(name, bases, attrs)
                cls.log = logging.getLogger('%s.%s' % (attrs['__module__'], name))
        def __init__(self):
            self.log.info('here I am, a %s!' % type(self).__name__)
    
    if __name__ == '__main__':
        logging.basicConfig(level=logging.DEBUG)
        foo = Foo()
    

提交回复
热议问题