首页 > 解决方案 > Python 日志记录,“KeyError:上下文”

问题描述

我正在尝试为一个模块设置子日志记录,让我们child_module在另一个模块中调用它parent_module

parent_module我这样称呼child_module

class ParentModule(object):
    def __init__(self,
                 logger,
                 child_module=None):
        self.logger = logger

        # set-up the child module
        self.child_module = child_module

        if child_module is None:
            self.child_module = ChildModule(
                logger=logging.getLogger('log.parent_module.child_module')
            )

if __name__ == '__main__':

    # Configure logger:
    logger = logging.getLogger('log.parent_module')
    logger.setLevel(5)

    formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
    handler = logging.StreamHandler(sys.stdout)
    handler.setFormatter(formatter)
    logger.addHandler(handler)

    p = ParentModule(logger=logger)

其中 log 是根日志库。在 child_module 中,主要功能是相同的,除了我们将日志定义为log.child_module. 当我运行它时,我得到以下回溯:

--- Logging error ---
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/logging/__init__.py", line 992, in emit
    msg = self.format(record)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/logging/__init__.py", line 838, in format
    return fmt.format(record)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/logging/__init__.py", line 578, in format
    s = self.formatMessage(record)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/logging/__init__.py", line 547, in formatMessage
    return self._style.format(record)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/logging/__init__.py", line 391, in format
    return self._fmt % record.__dict__
KeyError: 'context'

我找不到任何关于日志模块中应该存在的“上下文”变量的信息,而且我自己也没有定义任何自定义的日志变量。

标签: pythonpython-3.xloggingkeyerror

解决方案


推荐阅读