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

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

问题描述

在 Django 中,我到处都有记录器,目前使用硬编码的名称.

对于模块级日志记录(即,在视图函数的模块中),我有这样做的冲动.

log = logging.getLogger(__name__)

对于类级别的日志记录(即,在类 __init__ 方法中)我有这样做的冲动.

self.log = logging.getLogger("%s.%s" % (self.__module__, self.__class__.__name__))

在处理几十次 getLogger("hard.coded.name") 之前,我正在寻找第二种意见.

这行得通吗?还有其他人用同样缺乏想象力的方式命名他们的记录器吗?

此外,我应该分解并为此日志定义编写一个类装饰器吗?

解决方案

我通常不使用或发现需要类级别的记录器,但我最多将我的模块保留在几个类中.一个简单的:

导入日志LOG = logging.getLogger(__name__)

在模块顶部及后续:

LOG.info('垃圾邮件和鸡蛋很好吃!')

从文件中的任何位置通常可以让我到达我想去的地方.这避免了到处都需要 self.log 的需要,这往往会困扰我从每个类的角度来看,并使我的 5 个字符更接近 79 个字符行.

你总是可以使用伪类装饰器:

<预><代码>>>>导入日志>>>类 Foo(对象):... def __init__(self):... self.log.info('Meh')...>>>定义日志类(cls):... cls.log = logging.getLogger('{0}.{1}'.format(__name__, cls.__name__))...>>>登录类(Foo)>>>logging.basicConfig(level=logging.DEBUG)>>>f = Foo()信息:__main__.Foo:Meh

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?

解决方案

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

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

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