【问题标题】:Python Logging: Module information in imported modulesPython 日志记录:导入模块中的模块信息
【发布时间】:2017-07-21 16:50:53
【问题描述】:

我正在尝试在 python 日志记录中获得一些看起来很简单的东西。在调试日志记录期间,我想记录整个模块堆栈 -> 函数,但我无法让导入的类正确继承该信息。

我想要得到的示例:

module.imported_module.function - message
module.imported_module2.function - message
module.imported_module3.imported_module.function - message

我已经能够使用 logging.getLogger(file) 正确填充基本模块名称,但是当我尝试想办法将其适当地传递给子模块时,我陷入了困境麻烦,因为 logging.getLogger() 在 logging.getLogger() 调用中需要父名称,例如:

logging.getLogger('module.submodule')

我觉得必须有一种简单的方法将此信息传递给导入的模块和类,但我似乎无法找到一种不涉及为日志记录模块制作临时文件以供参考的方法,因为我正在运行它,这并不理想。

感谢您的任何帮助 - 即使只是“闭嘴,仔细观察” - 因为我似乎找不到合适的关键字来获得类似的东西。

这是我的 module.py 代码:

#!/usr/bin/python

import logging
import aux
import sys
from autologging import logged

logging.basicConfig(
    level=logging.DEBUG, stream=sys.stdout,
    format="%(levelname)s:%(name)s:%(funcName)s:%(message)s")
logger = logging.getLogger(__name__)


def print_names():
    logger.info('test info')
    logger.debug('test debug')
    logger.error('test error')
    aux.printme()


if __name__ == '__main__':
    print_names()

对于 aux.py:

#!/usr/bin/python
import logging
from autologging import logged


logger = logging.getLogger(__name__)
def printme():
    logger.info('test info')
    logger.debug('test debug')
    logger.error('test error')

我目前得到的输出:

bub@bubdev:~/tools/$ ./module.py 
INFO:__main__:print_names:test info
DEBUG:__main__:print_names:test debug
ERROR:__main__:print_names:test error
INFO:aux:printme:test info
DEBUG:aux:printme:test debug
ERROR:aux:printme:test error

我想得到什么:

bub@bubdev:~/tools/$ ./module.py 
INFO:__main__:print_names:test info
DEBUG:__main__:print_names:test debug
ERROR:__main__:print_names:test error
INFO:__main__:print_names:aux:printme:test info
DEBUG:__main__:print_names:aux:printme:test debug
ERROR:__main__:print_names:aux:printme:test error

【问题讨论】:

    标签: python logging


    【解决方案1】:

    您为什么不按照the documentation 中的说明使用logging.getLogger(__name__)

    【讨论】:

    • 这仅适用于一个级别,但不适用于它导入的模块。我会澄清我在这个问题中想要做什么。
    • 我使用了自动记录来使它更容易,但我仍然遇到同样的问题,它没有显示有关导入另一个模块的模块的信息(就像在 aux.py 中一样,它只显示 aux .py,而不是调用它的模块)。我只是误解了 logging.getLogger(name) 的用法吗?
    • 在更多地使用日志记录之后,我明白为什么我所做的事情是愚蠢的。无论如何,感谢您的回答。 :)
    猜你喜欢
    • 2016-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-25
    • 2016-01-13
    • 2011-11-29
    • 2021-11-23
    • 2020-08-11
    相关资源
    最近更新 更多