“RootLogger”的实例没有“trace”成员(但无法推断某些类型)

2024-10-01 13:34:07 发布

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

我有以下测试脚本,它模拟了我通常设置扩展记录器的操作:

import logging

TRACE_LL      = 25
TRACE_LSTR    = 'TRACE'
LOG_FORMATTER = '%(asctime)s - %(levelname)-10s - %(message)s'

class MyLogger(logging.Logger):

    def __init__(self, log_name):
        logging.Logger.__init__(self, log_name)
        self.setLevel(TRACE_LL)
        hdlr = logging.StreamHandler()
        formatter = logging.Formatter(LOG_FORMATTER)
        hdlr.setFormatter(formatter)
        self.addHandler(hdlr)

    def trace(self, txt, *args, **kwargs):
        self.log(TRACE_LL, txt, *args, **kwargs)

def getlog(name):
    return logging.getLogger(name)

def setup():
    logging.setLoggerClass(MyLogger)
    logging.addLevelName(TRACE_LL, TRACE_LSTR)
setup()

log = getlog('mylog')
log.trace('Trace this')

按预期运行此程序:

^{pr2}$

但是在这上面运行pylint会带来麻烦:

» pylint -E getlog_test.py
No config file found, using default configuration
************* Module getlog_test
E: 29,0: Instance of 'RootLogger' has no 'trace' member (but some types could not be inferred)

我在我的代码库中收到数百条这样的消息,因为我广泛地使用日志记录。在

如何解决pylint错误?在

另外,禁用它也足够了,但仅限于RootLogger实例:我仍然想知道代码的其他部分是否存在此问题。在


Tags: nameselflogformatterloggingdeftracepylint
2条回答

虽然我觉得pylint很有价值,但根据我的经验,它会产生许多错误和错误。通过在代码周围添加以下形式的注释,可以禁用对代码任何行的一个或多个检查:

# pylint: disable=E1103
code that pylint trips over
# pylint: enable=E1103

其中,E1103是要抑制的误差。可以使用逗号分隔的错误代码列表以相同的方式抑制多个错误。Pylint的文档是here。在

这是因为Pylint不够聪明,无法理解在调用getLogger时会得到MyLogger实例。在

除了使用消息的内联启用/禁用(一开始比较容易),您可能还想看看pylint brain项目(https://bitbucket.org/logilab/pylint-brain)。在

您将发现如何编写一个小的astroid插件,它可以向默认日志记录程序添加一个“trace”方法(或者更好地,通知logging.getLogger()returnMyLogger实例,但这有点棘手)。在

从长远来看,这肯定会更好。在

相关问题 更多 >