python - 在 python 中获取更有用的 'logging' 模块错误输出

标签 python python-3.x

我正在使用 python 的 logger 模块(python 版本 3.x,但应该无关紧要),我注意到格式字符串中的错误是这样报告的:

Traceback (most recent call last):
  File "/usr/lib/python3.1/logging/__init__.py", line 770, in emit
    msg = self.format(record)
  File "/usr/lib/python3.1/logging/__init__.py", line 650, in format
    return fmt.format(record)
  File "/usr/lib/python3.1/logging/__init__.py", line 438, in format
    record.message = record.getMessage()
  File "/usr/lib/python3.1/logging/__init__.py", line 308, in getMessage
    msg = msg % self.args
TypeError: %d format: a number is required, not str

如您所见,没有提及实际错误(在我的代码中)在哪里。顺便说一句,这是我的代码中的错误:

logging.debug('This is a string %d', str(foo))

更改 %s 中的 %d 解决了问题。

我的问题是:如何从 logging 模块输出中获得一些稍微更有用的信息?我必须编写自己的记录器吗?我在哪里调整 logger 模块?

最佳答案

如果我对您的理解正确,这里的问题是回溯不会给您任何指示,说明错误源自您的代码中的哪个位置。你必须以某种方式追踪这条线

logging.debug('This is a string %d', str(foo))

你自己。

日志记录模块的设计使得在 emit() 调用期间发生的异常由处理程序的 handleError 方法处理:

def handleError(self, record):
    """
    Handle errors which occur during an emit() call.

    This method should be called from handlers when an exception is
    encountered during an emit() call. If raiseExceptions is false,
    exceptions get silently ignored. This is what is mostly wanted
    for a logging system - most users will not care about errors in
    the logging system, they are more interested in application errors.
    You could, however, replace this with a custom handler if you wish.
    The record which was being processed is passed in to this method.
    """

您可以覆盖此方法以查看完整的回溯:

    import sys
    import logging

    class MyStreamHandler(logging.StreamHandler):
        def handleError(self, record):
            raise

    if __name__ == '__main__':
        console = MyStreamHandler()
        logger=logging.getLogger(__name__)
        logger.setLevel(logging.DEBUG)
        logger.addHandler(console)
        logger.debug('%d','ahh')

产量

Traceback (most recent call last):
  File "/tmp/test.py", line 25, in <module>
    logger.debug('%d','ahh')
  File "/usr/lib/python2.6/logging/__init__.py", line 1036, in debug
    self._log(DEBUG, msg, args, **kwargs)
  File "/usr/lib/python2.6/logging/__init__.py", line 1165, in _log
    self.handle(record)
  File "/usr/lib/python2.6/logging/__init__.py", line 1175, in handle
    self.callHandlers(record)
  File "/usr/lib/python2.6/logging/__init__.py", line 1212, in callHandlers
    hdlr.handle(record)
  File "/usr/lib/python2.6/logging/__init__.py", line 673, in handle
    self.emit(record)
  File "/usr/lib/python2.6/logging/__init__.py", line 796, in emit
    self.handleError(record)
  File "/usr/lib/python2.6/logging/__init__.py", line 768, in emit
    msg = self.format(record)
  File "/usr/lib/python2.6/logging/__init__.py", line 648, in format
    return fmt.format(record)
  File "/usr/lib/python2.6/logging/__init__.py", line 436, in format
    record.message = record.getMessage()
  File "/usr/lib/python2.6/logging/__init__.py", line 306, in getMessage
    msg = msg % self.args
TypeError: %d format: a number is required, not str

而使用通常的 StreamHandler,你只会得到:

Traceback (most recent call last):
  File "/usr/lib/python2.6/logging/__init__.py", line 768, in emit
    msg = self.format(record)
  File "/usr/lib/python2.6/logging/__init__.py", line 648, in format
    return fmt.format(record)
  File "/usr/lib/python2.6/logging/__init__.py", line 436, in format
    record.message = record.getMessage()
  File "/usr/lib/python2.6/logging/__init__.py", line 306, in getMessage
    msg = msg % self.args
TypeError: %d format: a number is required, not str

关于python - 在 python 中获取更有用的 'logging' 模块错误输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6898674/

相关文章:

python - Pandas 无法打开 csv 文件 FileNotFoundError

Python3 的 super 和 comprehensions -> TypeError?

python-3.x - 返回多维数组中N个最大值的索引(可以求一维的解,但不能求多维的)

python - 如何在 Falcon 中维护日志

python - 有什么方法可以将 PyTorch 中可用的预训练模型下载到特定路径?

python - 使用 CSS 选择器和 BeautifulSoup 获取属性值

python - 在 Django 中测试 POST 端点时如何包含 csrf token ?

python - 无法创建 django 模型的新实例

Python-Lex-Yacc 符号无法访问

python-3.x - botocore.exceptions.ClientError : An error occurred (ExpiredTokenException) The security token included in the request is expired