使用 Structlog 获取最后一个日志值并将其作为变量传递给函数

Getting last log value with Structlog and passing it as a variable to a function

目前我正在尝试实现一个函数调用,该函数调用将失败的消息从转换器发送到 Kafka 的 DLQ 主题。作为 DLQ 消息的一部分,我想包括我们也记录的异常错误。

代码:

except json.decoder.JSONDecodeError:
          log.error('failed to parse json',
                    topic=msg.topic(),
                    partition=msg.partition(),
                    offset=msg.offset()
                    )                                 
          produce_dlq_message(converters.get("DLQ"), msg, error_message)

我需要获取最新的 log.error() 调用的值并将其分配给变量:error_message

我在另一个异常块中调用了这个完全相同的函数,但它在 log.error() 调用中有不同的值,所以我需要一些东西来获取 last/latest 错误消息。

虽然可能有一种方法可以通过 multistructlog、处理器等实现这一点,但我建议采用低技术路线:

try:
   ...
except json.decoder.JSONDecodeError:
    em = {
        "event": "failed to parse json",
        "topic": msg.topic(),
        "partition": msg.partition(),
        "offset": msg.offset(),
    }

    log.error(**em)
    produce_dlq_message(converters.get("DLQ"), msg, json.dumps(em))

这意味着 em 被序列化了两次,但我认为总的来说它的简单性是值得的。

最后我用了这个方案

try:
   ...
except json.decoder.JSONDecodeError as e:
   log.error("failed to parse json",
              topic=msg.topic(),
              partition=msg.partition(),
              offset=msg.offset(),
              )

    error_message = str(e)
    produce_dlq_message(converters.get("DLQ"), msg, error_message)