Python日志记录属性Error:模块“日志记录”没有属性“处理程序”

2024-04-19 17:19:37 发布

您现在位置:Python中文网/ 问答频道 /正文

观察:当我注释掉from logging import handlers时,观察到下面提到的错误

Error:
    file_handler =  logging.handlers.RotatingFileHandler(
AttributeError: module 'logging' has no attribute 'handlers'

问题:如果我已经导入了logging,为什么需要执行from logging import handlers

import logging
import sys
#from logging import handlers

def LoggerDefination():
    #file_handler = logging.FileHandler(filename='..\\logs\\BasicLogger_v0.1.log', mode='a')
    file_handler =  logging.handlers.RotatingFileHandler(
        filename="..\\logs\\BasicLogger_v0.2.log",
        mode='a',
        maxBytes=20000,
        backupCount=7,
        encoding=None,
        delay=0
    )
    file_handler.setLevel(logging.DEBUG)

    stdout_handler = logging.StreamHandler(sys.stdout)
    stdout_handler.setLevel(logging.DEBUG)
    handlers = [file_handler, stdout_handler]

    logging.basicConfig(
        level=logging.DEBUG,
        format='%(asctime)s | %(module)s | %(name)s | LineNo_%(lineno)d | %(levelname)s |  %(message)s',
        handlers=handlers
    )

def fnt_test_log1():
    LoggerDefination()
    WriteLog1 = logging.getLogger('fnt_test_log1')
    #WriteLog1.propagate=False
    WriteLog1.info("######## START OF : test_log1 ##########")
    WriteLog1.debug("test_log1 | This is debug level")
    WriteLog1.debug("test_log1 | This is debug level")
    WriteLog1.info("test_log1 | This is info level")
    WriteLog1.warning("test_log1 | This is warning level")
    WriteLog1.error("test_log1 | This is error level")
    WriteLog1.critical("test_log1 |This is critiacl level")
    WriteLog1.info("######## END OF : test_log1 ##########")


def fnt_test_log2():
    LoggerDefination()
    WriteLog2 = logging.getLogger('fnt_test_log2')
    WriteLog2.info("######## START OF : test_log2 ##########")
    WriteLog2.debug("test_log2 ===> debug")
    WriteLog2.debug("test_log2 | This is debug level")
    WriteLog2.debug("test_log2 | This is debug level")
    WriteLog2.info("test_log2 | This is info level")
    WriteLog2.warning("test_log2 | This is warning level")
    WriteLog2.error("test_log2 | This is error level")
    WriteLog2.critical("test_log2 |This is critiacl level")
    WriteLog2.info("######## STOP OF : test_log2 ##########")


if __name__ == '__main__':
    LoggerDefination()
    MainLog = logging.getLogger('main')
    LoggerDefination()
    MainLog.info("Executing script: " + __file__)
    fnt_test_log1()
    fnt_test_log2()

Tags: debugtestinfoislogginghandlersthislog2
2条回答

也许您有一些名为logging其他模块,它屏蔽了标准库。您的代码库中是否有名为logging.py的文件

这是一个由两部分组成的答案:第一部分是关于你眼前的问题。第二部分是关于为什么你的问题会首先出现的问题(以及,考虑到你的问题已经两个月了,我是如何在这条线索中结束的)

第一部分(您问题的答案):当导入像import logging这样的包时,Python默认情况下从不导入像logging.handlers这样的子包(或子模块),而只向您公开在包的__init__.py文件中定义的变量(在本例中为logging/__init__.py)。不幸的是,很难从外部判断logging.handlerslogging/__init__.py中的变量还是实际的独立模块logging/handlers.py。所以你必须看一下logging/__init__.py,然后你会发现它没有定义一个handlers变量,而是有一个模块logging/handlers.py,你需要通过import logging.handlersfrom logging.handlers import TheHandlerYouWantToUse单独导入。这应该能回答你的问题

第二部分:我最近注意到我的IDE(PyCharm)总是建议import logging,只要我真的想使用logging.handlers.QueueHandler。出于某种神秘的原因(尽管我在第一部分中说过),它一直在工作…嗯,大多数时候

具体地说,在下面的代码中,类型注释导致预期的AttributeError: module 'logging' has no attribute 'handlers'。但是,在注释掉注释(对于Python<;3.9,注释在模块执行期间执行)之后,调用函数是有效的——前提是我将其称为“足够晚”(下面将详细介绍)

import logging
from multiprocessing.queues import Queue


def redirect_logs_to_queue(
    logging_queue: Queue, level: int = logging.DEBUG
) -> logging.handlers.QueueHandler:  # <                 This fails

    queue_handler = logging.handlers.QueueHandler(logging_queue)  # < - This works
    root = logging.getLogger()
    root.addHandler(queue_handler)
    root.setLevel(level)
    return queue_handler

那么,“足够晚”是什么意思呢?不幸的是,我的应用程序太复杂了,无法快速查找bug。然而,我很清楚logging.handlers必须在启动(即所有模块都被加载/执行)和调用该函数之间的某个时间点“可用”。这给了我一个决定性的提示:事实证明,包层次结构深处的另一个模块正在执行from logging.handlers import RotatingFileHandler, QueueListener。该语句加载了整个logging.handlers模块,并导致Python在其父包logging中“挂载”了handlers模块,这意味着logging变量此后将始终配备handlers属性,即使仅仅在import logging之后,这就是我不再需要import logging.handlers的原因(这可能是皮查姆注意到的)

你自己试试看:

这项工作:

import logging
from logging.handlers import QueueHandler
print(logging.handlers)

这并不是:

import logging
print(logging.handlers)

总而言之,这种现象是Python的导入机制使用全局状态来避免重新加载模块的结果(这里,我指的“全局状态”是在import logging时得到的logging变量)在多个模块中,您不希望logging.handlers模块中的代码被加载(并因此执行!)多次。因此,Python只需在您将logging.handlers导入某处时将handlers属性添加到logging模块对象中,并且由于import logging共享相同的logging对象,因此logging.handlers会突然变得随处可见

相关问题 更多 >