Python记录 - 将附段字段添加到自定义格式化

发布于 2025-02-11 10:16:09 字数 2391 浏览 1 评论 0原文

我已经有以下用于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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

放肆 2025-02-18 10:16:09

您面临的问题是,您成功地将属性添加到记录中,但是您的格式化者只是忽略了它。别无选择,只能更改或替换您正在使用的自定义形式。可能的解决方案可能看起来像这样:

class CustomFormatterExtra(CustomFormatter):
    custom_name = 'custom_attribute'

    def formatMessage(self, record, *args, **kwargs):
        json_str = super().formatMessage(record, *args, **kwargs)
        if hasattr(record, self.custom_name):
            json_dict = json.loads(json_str)
            json_dict[self.custom_name] = getattr(record, self.custom_name)
            json_str = json.dumps(json_dict)
        return json_str


logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logger_handler = logging.StreamHandler()
logger_handler.setFormatter(CustomFormatterExtra())
logger.addHandler(logger_handler)

logger.info("Ich bin ein Test", extra={'custom_attribute':123})
CustomFormatterExtra.custom_name = 'different_attribute'
logger.info("Ich bin ein Test", extra={'different_attribute':123})

请注意,这不需要自定义的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:

class CustomFormatterExtra(CustomFormatter):
    custom_name = 'custom_attribute'

    def formatMessage(self, record, *args, **kwargs):
        json_str = super().formatMessage(record, *args, **kwargs)
        if hasattr(record, self.custom_name):
            json_dict = json.loads(json_str)
            json_dict[self.custom_name] = getattr(record, self.custom_name)
            json_str = json.dumps(json_dict)
        return json_str


logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logger_handler = logging.StreamHandler()
logger_handler.setFormatter(CustomFormatterExtra())
logger.addHandler(logger_handler)

logger.info("Ich bin ein Test", extra={'custom_attribute':123})
CustomFormatterExtra.custom_name = 'different_attribute'
logger.info("Ich bin ein Test", extra={'different_attribute':123})

Note that this does not need a custom LogRecord factory. The extra param does exactly what yours did.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文