You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在GCP中以JSON格式将LogRecord属性纳入日志信息?

将LogRecord属性作为JSON payload发送至GCP日志

要把LogRecord的processName、threadName、exc_info等属性和自定义日志数据一起以JSON格式发送到GCP,你需要自定义日志格式化器,提取LogRecord的核心属性并与自定义数据合并,再传递给GCP的日志处理器。

实现步骤与代码示例

  1. 自定义结构化日志格式化器:继承logging.Formatter,在format方法中提取LogRecord属性,处理异常信息,并合并自定义JSON数据。
  2. 配置GCP日志处理器:创建CloudLoggingHandler并绑定自定义格式化器,添加到目标logger中。

完整代码如下:

import logging
import google.cloud.logging
from google.cloud.logging_v2.handlers import CloudLoggingHandler
import json

class StructuredFormatter(logging.Formatter):
    def format(self, record):
        # 提取LogRecord核心属性
        structured_data = {
            "process_name": record.processName,
            "thread_name": record.threadName,
            "log_level": record.levelname,
            "logger_name": record.name,
            "timestamp": self.formatTime(record, "%Y-%m-%dT%H:%M:%S.%fZ"),
            "module": record.module,
            "function": record.funcName,
            "line_no": record.lineno
        }
        
        # 处理异常栈信息(仅当日志包含异常时)
        if record.exc_info:
            structured_data["exception_stacktrace"] = self.formatException(record.exc_info)
        
        # 合并自定义日志数据:若日志消息是JSON字符串则解析合并,否则保留为message字段
        try:
            custom_data = json.loads(record.getMessage())
            structured_data.update(custom_data)
        except json.JSONDecodeError:
            structured_data["message"] = record.getMessage()
        
        return json.dumps(structured_data)

# 初始化GCP日志客户端
client = google.cloud.logging.Client()

# 创建并配置GCP日志处理器
handler = CloudLoggingHandler(client)
handler.setFormatter(StructuredFormatter())

# 配置目标logger
logger = logging.getLogger('test')
logger.setLevel(logging.INFO)
logger.addHandler(handler)

# 测试:发送带自定义数据的日志
data_dict = {"hello": "world"}
logger.info(json.dumps(data_dict))

# 测试:发送带异常信息的日志
try:
    1 / 0
except ZeroDivisionError:
    logger.exception("Division by zero error")

效果说明

  • 发送的日志在GCP日志控制台中,jsonPayload会包含所有提取的LogRecord属性(如process_name、thread_name)以及自定义数据(如hello: "world")。
  • 使用logger.exception()时,异常栈信息会自动存入exception_stacktrace字段,方便排查问题。

内容的提问来源于stack exchange,提问作者majain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 05:35:21