Python记录 - 将附段字段添加到自定义格式化
我已经有以下用于Logger的格式化类别,该类别在我们的公司Libary中使用:
import json
import logging
from typing import Optional
class CustomFormatter(logging.Formatter):
def __init__(
self,
fmt: Optional[str] = "%(asctime)s",
datefmt: Optional[str] = None,
style: Optional[str] = "%",
confidentiality: Optional[str] = "C3",
) -> None:
self.confidentiality = confidentiality
super().__init__(fmt=fmt, datefmt=datefmt, style=style)
def formatMessage(self, record: logging.LogRecord, *args, **kwargs) -> str:
super().formatMessage(record)
return json.dumps(
{
"asctime": record.asctime,
"level": record.levelname,
"name": record.name,
"message": record.message,
"timeMillis": int(record.created * 1000),
"pathName": record.pathname,
"funcName": record.funcName,
"lineNumber": record.lineno,
"confidentiality": self.confidentiality,
}
)
我尝试添加这样的自定义字段:
old_factory = logging.getLogRecordFactory()
def record_factory(*args, **kwargs):
record = old_factory(*args, **kwargs)
record.custom_attribute = "my-attr"
return record
logging.setLogRecordFactory(record_factory)
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logger_handler = logging.StreamHandler()
logger_handler.setFormatter(CustomFormatter())
logger.addHandler(logger_handler)
logger.info("Ich bin ein Test")
结果:
{"asctime": "2022-06-29 10:40:22,869", "level": "INFO", "name": "root", "message": "test", "timeMillis": 1656492022869, "pathName": "C:\\Users\\xcg5847\\Desktop\\loggingnew\\test.py", "funcName": "<module>", "lineNumber": 15, "
confidentiality": "C3"}
尚未添加。我猜问题是,格式化器总是返回相同的JSON对象,这本身是不可扩展的。
这就是我想要的:
{"asctime": "2022-06-29 10:40:22,869", "level": "INFO", "name": "root", "message": "test", "timeMillis": 1656492022869, "pathName": "C:\\Users\\xcg5847\\Desktop\\loggingnew\\test.py", "funcName": "<module>", "lineNumber": 15, "
confidentiality": "C3", "custom_attribute": "my-attr"}
重要:理想情况下,这将是这样起作用的:
logger.info("test", extra={"custom_attribute": "my-attr"}
I have got the following formatter class for a Logger, which is used in our companies libary:
import json
import logging
from typing import Optional
class CustomFormatter(logging.Formatter):
def __init__(
self,
fmt: Optional[str] = "%(asctime)s",
datefmt: Optional[str] = None,
style: Optional[str] = "%",
confidentiality: Optional[str] = "C3",
) -> None:
self.confidentiality = confidentiality
super().__init__(fmt=fmt, datefmt=datefmt, style=style)
def formatMessage(self, record: logging.LogRecord, *args, **kwargs) -> str:
super().formatMessage(record)
return json.dumps(
{
"asctime": record.asctime,
"level": record.levelname,
"name": record.name,
"message": record.message,
"timeMillis": int(record.created * 1000),
"pathName": record.pathname,
"funcName": record.funcName,
"lineNumber": record.lineno,
"confidentiality": self.confidentiality,
}
)
I tried to add custom fields like this:
old_factory = logging.getLogRecordFactory()
def record_factory(*args, **kwargs):
record = old_factory(*args, **kwargs)
record.custom_attribute = "my-attr"
return record
logging.setLogRecordFactory(record_factory)
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logger_handler = logging.StreamHandler()
logger_handler.setFormatter(CustomFormatter())
logger.addHandler(logger_handler)
logger.info("Ich bin ein Test")
Result:
{"asctime": "2022-06-29 10:40:22,869", "level": "INFO", "name": "root", "message": "test", "timeMillis": 1656492022869, "pathName": "C:\\Users\\xcg5847\\Desktop\\loggingnew\\test.py", "funcName": "<module>", "lineNumber": 15, "
confidentiality": "C3"}
This is not being added. I guess the problem is that, the formatter always returns that same json object and that this is per se not extensible the way it was build.
This is what I desire:
{"asctime": "2022-06-29 10:40:22,869", "level": "INFO", "name": "root", "message": "test", "timeMillis": 1656492022869, "pathName": "C:\\Users\\xcg5847\\Desktop\\loggingnew\\test.py", "funcName": "<module>", "lineNumber": 15, "
confidentiality": "C3", "custom_attribute": "my-attr"}
IMPORTANT: Ideally this would work like this:
logger.info("test", extra={"custom_attribute": "my-attr"}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您面临的问题是,您成功地将属性添加到记录中,但是您的格式化者只是忽略了它。别无选择,只能更改或替换您正在使用的自定义形式。可能的解决方案可能看起来像这样:
请注意,这不需要自定义的Logrecord工厂。
Extra
param确实做了您所做的。The Problem you are facing is, that you successfully add the attribute to the Record but your formatter just ignores it. There is no way around that but to either change or replace the CustomFormatter that you are using. A possible solution could look like this:
Note that this does not need a custom LogRecord factory. The
extra
param does exactly what yours did.