在Python日志记录中为每个日志消息添加信息

6

我正在使用Python的logging模块,并且希望将socket.hostname()添加到每条日志消息中,我必须运行此查询来处理每个消息,无法使用

name = socket.hostname() 

然后使用名称格式记录日志

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

我该如何实现所需的结果?


如何装饰日志记录函数? - Boseong Choi
2个回答

5

在使用dictConfig的基础上,借鉴了Philippe的回答。该回答中演示的上下文过滤器使用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

注意,对我而言过滤函数并没有生效,仅有过滤类才有效。
接下来,根据这个答案更新你的日志配置字典,如下所示:(链接)
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% 的内存使用率。

4
您可以使用过滤器向每个消息添加信息:
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')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接