避免使用logger = logging.getLogger(__ name__)而不丢失过滤日志的方法 [英] Avoid `logger=logging.getLogger(__name__)` without loosing way to filter logs
问题描述
我很懒,并且希望在每个使用日志记录的python文件中避免出现这一行:
I am lazy and want to avoid this line in every python file which uses logging:
logger = logging.getLogger(__name__)
在一月份,我问如何做到这一点,并找到了答案:避免`logger = logging.getLogger(__ name __)`
In january I asked how this could be done, and found an answer: Avoid `logger=logging.getLogger(__name__)`
不幸的是,那里的答案有一个缺点,那就是您失去了过滤功能.
Unfortunately the answer there has the drawback, that you loose the ability to filter.
我真的想避免这条无用和多余的线.
I really want to avoid this useless and redundant line.
示例:
import logging
def my_method(foo):
logging.info()
不幸的是,如果第一次在该文件中调用logging.info()
,我认为不可能隐式地执行logger = logging.getLogger(__name__)
.
Unfortunately I think it is impossible do logger = logging.getLogger(__name__)
implicitly if logging.info()
gets called for the first time in this file.
外面有人知道怎么做不可能的事情吗?
Is there anybody out there who knows how to do impossible stuff?
更新
我喜欢不要重复自己.如果大多数文件的顶部都包含同一行,则我认为这是重复.看起来像是 WET .每当我看到那里时,脑海中的python解释器都需要跳过此行.我的主观感觉:这条线是没用的膨胀.该行应为隐式默认值.
I like Don't Repeat Yourself. If most files contain the same line at the top, I think this is a repetition. It looks like WET. The python interpreter in my head needs to skip this line every time I look there. My subjective feeling: this line is useless bloat. The line should be the implicit default.
推荐答案
我很懒,我想在每个使用 记录:
I am lazy and want to avoid this line in every python file which uses logging:
logger = logging.getLogger(__name__)
好吧,这是推荐的方式:
Well, it's the recommended way:
命名记录器时要使用的一个很好的约定是使用模块级 记录器,在使用日志记录的每个模块中,命名如下:
A good convention to use when naming loggers is to use a module-level logger, in each module which uses logging, named as follows:
logger = logging.getLogger(__name__)
这意味着记录器名称跟踪程序包/模块的层次结构,并且 从直观上很明显,仅从记录器记录事件的位置 名称.
This means that logger names track the package/module hierarchy, and it’s intuitively obvious where events are logged just from the logger name.
这是来自官方 howto 的引用.
That's a quote from the official howto.
我喜欢不要重复自己.如果大多数文件在以下位置包含同一行: 顶部,我认为这是重复.看起来像WET.蟒蛇 每当我看时,脑海中的口译员都需要跳过这一行 那里.我的主观感觉:这条线是没用的膨胀.线 应该是隐式默认值.
I like Don't Repeat Yourself. If most files contain the same line at the top, I think this is a repetition. It looks like WET. The python interpreter in my head needs to skip this line every time I look there. My subjective feeling: this line is useless bloat. The line should be the implicit default.
它遵循显式优于隐式".无论如何,您可以轻松地在许多IDE中更改python模板,以始终包含此行或创建新的模板文件.
It follows "Explicit is better than implicit". Anyway you can easily change a python template in many IDEs to always include this line or make a new template file.
这篇关于避免使用logger = logging.getLogger(__ name__)而不丢失过滤日志的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!