命名 Python 记录器
在 Django 中,我到处都有记录器,目前使用硬编码名称。
对于模块级日志记录(即在视图函数的模块中),我有这样做的冲动。
log = logging.getLogger(__name__)
对于类级别的日志记录(即在类 __init__
方法中),我有这样做的冲动。
self.log = logging.getLogger("%s.%s" % (
self.__module__, self.__class__.__name__))
在处理数十次出现的 getLogger("hard.coded.name")
之前,我正在寻求第二意见。
这行得通吗? 还有其他人用同样缺乏想象力的方式命名他们的记录器吗?
此外,我应该分解并为这个日志定义编写一个类装饰器吗?
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 do this.
log = logging.getLogger(__name__)
For class-level logging (i.e., in a class __init__
method) I have the urge to do this.
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")
.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我通常不使用或不需要类级记录器,但我最多将模块保留在几个类中。 一个简单的:
在模块的顶部和后续:
从文件中的任何位置通常可以让我到达我想要的位置。 这避免了到处都需要
self.log
,这往往会从将其放入每个类的角度困扰我,并使我的 5 个字符更接近 79 个适合的字符行。您始终可以使用伪类装饰器:
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:
At the top of the module and subsequent:
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:
对于类级别日志记录,作为伪类装饰器的替代方案,您可以使用元类在类创建时为您创建记录器......
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...
看起来它会起作用,除了
self
没有__module__
属性; 它的阶级将会。 类级记录器调用应如下所示:That looks like it will work, except that
self
won't have a__module__
attribute; its class will. The class-level logger call should look like: