这基于 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% 的内存使用率。