[英]Naming Python loggers
In Django, I've got loggers all over the place, currently with hard-coded names. 在Django,我到处都有记录器,目前有硬编码的名字。
For module-level logging (ie, in a module of view functions) I have the urge to do this. 对于模块级日志记录(即,在视图函数模块中),我有这样做的冲动。
log = logging.getLogger(__name__)
For class-level logging (ie, in a class __init__
method) I have the urge to do this. 对于类级别的日志记录(即,在类__init__
方法中),我有这样做的冲动。
self.log = logging.getLogger("%s.%s" % (
self.__module__, self.__class__.__name__))
I'm looking for second opinions before I tackle several dozen occurrences of getLogger("hard.coded.name")
. 在我解决几十次出现的getLogger("hard.coded.name")
之前,我正在寻找第二意见。
Will this work? 这会有用吗? Anyone else naming their loggers with the same unimaginative ways? 还有其他人用同样缺乏想象力的方式命名他们的记录器吗?
Further, should I break down and write a class decorator for this log definition? 此外,我应该分解并为此日志定义编写类装饰器吗?
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. 这样可以避免在整个地方都需要self.log
,这往往会让我从每个类中放入一个令人困扰的角度,并使我更接近于符合79个字符行的5个字符。
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
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()
That looks like it will work, except that self
won't have a __module__
attribute; 看起来它会起作用,除了self
不会有__module__
属性; its class will. 它的班级会。 The class-level logger call should look like: 类级记录器调用应如下所示:
self.log = logging.getLogger( "%s.%s" % ( self.__class__.__module__, self.__class__.__name__ ) )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.