drj*_*ild 3 python logging python-3.x python-3.5
再会。我正在尝试解决Python 中的登录问题。我正在使用Python 3.5.1。我有一个应用程序,它使用从其他模块导入的类。我无法为其启用日志记录。这是一个简单的表示:
# test.py
import logging
from test_class import TestClass
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.FileHandler('test_log.log', mode='w'))
if __name__ == '__main__':
logger.info('Importing class')
t = TestClass()
t.make_call()
t.make_another_call()
logger.info('End')
# test_class.py
import logging
class TestClass(object):
def __init__(self):
self.logger = logging.getLogger('test_class.TestClass')
def make_call(self):
self.logger.info('Make a call')
def make_another_call(self):
self.logger.info('Make another call')
Run Code Online (Sandbox Code Playgroud)
如您所见,记录器必须写入文件行(两行来自主模块,两行来自类。但是当我打开日志文件时,我看到:
# test_log.log
Importing class
End
Run Code Online (Sandbox Code Playgroud)
因此,来自类的两个记录器调用没有效果。知道吗,为什么它不起作用?先感谢您。
来自文档:
\n\n\n多次调用同名的 getLogger() 将始终返回对同一 Logger 对象的引用。
\n该名称可能是一个以句点分隔的层次结构值,例如 foo.bar.baz(尽管它也可能只是普通的 foo)。层次结构列表中靠下的记录器是列表中靠上的记录器的子项。例如,给定一个名为 foo 的记录器,名称为 foo.bar、foo.bar.baz 和 foo.bam 的记录器都是 foo 的后代。记录器名称层次结构类似于 Python 包层次结构,如果您使用推荐的结构在每个模块的基础上组织记录器,则它是相同的
\nlogging.getLogger(__name__)。\xe2\x80\x99s 因为在模块中,__name__是 Python 包命名空间中的模块\xe2\x80\x99s 名称。
您在代码中调用的方式getLogger,调用test.py是通过 完成的__main__,调用test_class.py是通过 完成的test_class,因此后者不是前者的后代。
相反,如果在设置处理程序时,您在getLogger()不带参数的调用中获得的对象上执行此操作,那么您将在根日志记录对象上设置处理程序,并且所有其他调用将在getLogger()层次结构中进一步向下并使用您指定的处理程序。
如果您想继续在主模块中为日志记录语句设置名称,则可以getLogger在设置处理程序后再次调用。
例如:
\n# Call getLogger with no args to set up the handler\nlogger = logging.getLogger()\nlogger.setLevel(logging.DEBUG)\nlogger.addHandler(logging.FileHandler(\'test_log.log\', mode=\'w\'))\n\n\nif __name__ == \'__main__\':\n # call getLogger again with a name to tag subsequent log statements\n logger = logging.getLogger(__name__)\n logger.info(\'Importing class\')\n t = TestClass()\n t.make_call()\n t.make_another_call()\n logger.info(\'End\')\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
8699 次 |
| 最近记录: |