命名Python日志记录器 [英] Naming Python loggers

查看:104
本文介绍了命名Python日志记录器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Django中,我已经有了整个地方的记录器,目前使用硬编码的名称。

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__)

对于类级日志记录(即在一个类 __ init __ 方法中)有这样做的冲动。

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__))

我正在寻找第二个意见我解决了几十次出现的 getLogger(hard.coded.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?

推荐答案

我通常不会使用或找到对类级别的记录器的需要,但是我最多将模块保留在几个类中。一个简单的:

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__)

在模块的顶部和后面:

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

从文件的任何地方通常让我到我想要的地方。这避免了在这个地方需要 self.log ,这倾向于使我从一个放在每一个角度来看待我,使我5个字符更接近到79个符合条件的字符。

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

这篇关于命名Python日志记录器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆