Naming Python loggers

后端 未结 3 572
深忆病人
深忆病人 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:47

    I typically don't use or find a need for class-level loggers, but I keep my modules at a few classes at most. A simple:

    import logging
    LOG = logging.getLogger(__name__)
    

    At the top of the module and subsequent:

    LOG.info('Spam and eggs are tasty!')
    

    from anywhere in the file typically gets me to where I want to be. This avoids the need for self.log all over the place, which tends to bother me from both a put-it-in-every-class perspective and makes me 5 characters closer to 79 character lines that fit.

    You could always use a pseudo-class-decorator:

    >>> import logging
    >>> class Foo(object):
    ...     def __init__(self):
    ...             self.log.info('Meh')
    ... 
    >>> def logged_class(cls):
    ...     cls.log = logging.getLogger('{0}.{1}'.format(__name__, cls.__name__))
    ... 
    >>> logged_class(Foo)
    >>> logging.basicConfig(level=logging.DEBUG)
    >>> f = Foo()
    INFO:__main__.Foo:Meh
    

提交回复
热议问题