[英]Is there any difference in putting the logging statement in a module level vs in a class level?
module1.py module1.py
#!/usr/bin/env python
import logging
LOGGER = logging.getLogger(__main__)
class MyClass()
def __init__(self):
LOGGER.info('test')
Versus 与
module2.py module2.py
#!/usr/bin/env python
import logging
class MyClass()
def __init__(self):
self.LOGGER = logging.getLogger(__main__)
self.LOGGER.info('test')
Seems to me like module2.py will give some unpredictable outcome when imported by other modules. 在我看来,module2.py在被其他模块导入时会产生一些无法预测的结果。 I'm not sure though.
我不确定。
logging.getLogger()
returns a singleton (per given name); logging.getLogger()
返回一个单例(按给定名称); there's no difference in storing it as a module global or as an instance attribute. 将其存储为模块全局或实例属性没有区别。 Your code is referencing the same object in both cases.
在两种情况下,您的代码都引用相同的对象。
Quoting the documentation : 引用文档 :
Multiple calls to
getLogger()
with the same name will always return a reference to the same Logger object.对具有相同名称的
getLogger()
多次调用将始终返回对同一Logger对象的引用。
and from the logging.getLogger()
function itself: 和从
logging.getLogger()
函数本身:
All calls to this function with a given name return the same logger instance.
使用给定名称对该函数的所有调用均返回相同的记录器实例。 This means that logger instances never need to be passed between different parts of an application.
这意味着记录器实例永远不需要在应用程序的不同部分之间传递。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.