【问题标题】:Add information to every log message in Python logging向 Python 日志记录中的每条日志消息添加信息
【发布时间】:2020-06-26 17:26:19
【问题描述】:

我正在使用带有日志记录模块的 Python,并且想将 socket.hostname() 添加到每条日志消息中,我必须在每条消息中运行此查询并且不能使用

name = socket.hostname() 

然后使用名称记录格式

我正在研究this 使用日志过滤器的示例,但我在这里需要的不是过滤器,它是对每条日志消息的简单操作。

我怎样才能达到想要的结果?

【问题讨论】:

  • 日志功能如何修饰?

标签: python python-3.x logging


【解决方案1】:

您可以使用过滤器为每条消息添加信息:

import logging
import socket

class ContextFilter(logging.Filter):
    def filter(self, record):
        record.hostname = socket.gethostname() 
        return True

if __name__ == '__main__':
    levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)-15s hostname: %(hostname)-15s : %(message)s')
    a1 = logging.getLogger('a.b.c')
    f = ContextFilter()
    a1.addFilter(f)
    a1.debug('A debug message')

【讨论】:

    【解决方案2】:

    这基于 Philippe 在使用 dictConfig 时的回答。此答案中演示的contextual filter 使用psutil 在每条日志消息中记录当前的CPU 和内存使用百分比。

    将此文件保存为mypackage/util/logging.py:

    """logging utiliies."""
    import logging
    
    from psutil import cpu_percent, virtual_memory
    
    
    class PsutilFilter(logging.Filter):
        """psutil logging filter."""
    
        def filter(self, record: logging.LogRecord) -> bool:
            """Add contextual information about the currently used CPU and virtual memory percentages into the given log record."""
            record.psutil = f"c{cpu_percent():02.0f}m{virtual_memory().percent:02.0f}"  # type: ignore
            return True
    

    请注意,过滤功能对我不起作用;只有一个过滤器类起作用。

    接下来,根据this answer 更新您的日志记录配置字典,如下所示:

    LOGGING_CONFIG = {
        ...,
        "filters": {"psutil": {"()": "mypackage.util.logging.PsutilFilter"}},
        "handlers": {"console": {..., "filters": ["psutil"]}},
        "formatters": {
            "detailed": {
                "format": "%(asctime)s %(levelname)s %(psutil)s %(process)x:%(threadName)s:%(name)s:%(lineno)d:%(funcName)s: %(message)s"
            }
        },
    }
    

    尝试记录一些东西,并查看示例输出,例如:

    2020-05-16 01:06:08,973 INFO c68m51 3c:MainThread:mypackage.mymodule:27:myfunction: This is my log message.
    

    在上述消息中,c68m51 表示 68% 的 CPU 和 51% 的内存使用率。

    【讨论】:

      猜你喜欢
      • 2016-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-07
      • 2014-11-17
      • 1970-01-01
      • 2019-07-11
      • 1970-01-01
      相关资源
      最近更新 更多