【问题标题】:Python logging.conf reload configurationPython logging.conf 重载配置
【发布时间】:2019-07-08 10:06:38
【问题描述】:

在我的 python 代码中,我从一个文件中读取了日志记录配置,我在该文件中放置了我希望在我的代码中使用的格式。
当我尝试在运行时重新加载配置时,我放入格式化程序中的一些额外环境似乎丢失了,并且出现以下错误。

Traceback (most recent call last):
  File "/usr/lib64/python2.7/logging/__init__.py", line 861, in emit
    msg = self.format(record)
  File "/usr/lib64/python2.7/logging/__init__.py", line 734, in format
    return fmt.format(record)
  File "/usr/lib64/python2.7/logging/__init__.py", line 469, in format
    s = self._fmt % record.__dict__
KeyError: 'hostname'
Logged from file conn.py, line 304

注意我的 logging.conf 如下:

[formatter_simpleFormatter]
format=[%(levelname)s] %(asctime)s [ThId-%(threadName)-10s] [%(filename)s:%(funcName)s:%(lineno)s] [%(hostname)s] %(message)s
datefmt=%m/%d/%Y %I:%M:%S %p

其中 hostname 在代码中通过以下方式设置:

class HostnameFilter(logging.Filter):
    hostname = platform.node()

    def filter(self, record):
        record.hostname = HostnameFilter.hostname
        return True

## Log Logger.
class Logger:
    """!@brief
    Logger wrapper
    """
    def __init__(self):
        self.log = logging.getLogger("MYCONF")
        self.log.addFilter(HostnameFilter())

奇怪的是错误似乎出现在不是我的类(conn.py)中,也许这是我正在使用的一些库的代码,它们也在记录。

这是流量吗?我要不要做点别的?

【问题讨论】:

    标签: python logging filter configuration handler


    【解决方案1】:

    因为格式化发生在处理程序中,并且记录到记录器的事件被传递给该记录器的处理程序以及记录器层次结构更上层的处理程序,所以您需要确保始终将 hostname 属性添加到记录中- 如果使用不同的记录器来记录消息,情况可能并非如此。尝试将过滤器附加到相关的处理程序而不是记录器。

    【讨论】:

      猜你喜欢
      • 2017-08-21
      • 2015-04-16
      • 1970-01-01
      • 2015-06-11
      • 2014-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-21
      相关资源
      最近更新 更多