如何在Golang中将google cloud pubsub有效负载转换为LogEntry对象 &g



我创建了一个日志路由器Sink来将日志导出到Pub/Sub。我的Golang应用程序应该通过使用google客户端库(Golang)的专用订阅来消费来自这个Pub/Sub的消息。

订阅上收到的消息是LogEntry对象的JSON表示。

问题:如何将json解组为有用的Golang对象?

  • 我的第一次尝试是将json解编组到Entry对象。尝试失败,因为这个对象没有JSON映射的字段,特别是textPayloadJSON字段没有解组
  • 第二次尝试是将json解组为LogEntry对象。这个对象似乎符合定义,但它的主要目的是protobufs(而不是JSON)。特别是当我试图将LogEntry JSON解组到其中时,我得到了以下错误

不能将字符串反编组为Go结构体字段LogEntry。类型ltype的严重性。LogSeverity

如果你得到关于protoPayloadtimestamppb.Timestamp的错误,它可能是一个JSON表示的协议缓冲区。要在Go中marshal/Unmarshal协议缓冲区,你应该使用protojson包。例子:

import (
... omitted ...
_ "google.golang.org/genproto/googleapis/cloud/audit"
logging "google.golang.org/genproto/googleapis/logging/v2"
"google.golang.org/protobuf/encoding/protojson"
)
func handlerLogEntry(w http.ResponseWriter, r *http.Request) {
var le logging.LogEntry
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, "Bad HTTP Request", http.StatusBadRequest)
log.Printf("handlerLogEntry ReadAll error: %", err)
return
}
if err := protojson.Unmarshal(body, &le); err != nil {
http.Error(w, "Bad HTTP Request", http.StatusBadRequest)
log.Printf("handlerLogEntry Unmarshal error: %", err)
return
}
s := fmt.Sprintf("handlerLogEntry: %#v", le)
log.Printf(s)
fmt.Fprintln(w, s)
}

您试图解析的JSON包含字符串而不是整数。日志严重性代码应该是以下代码之一:

type LogSeverity int32
const (
// (0) The log entry has no assigned severity level.
LogSeverity_DEFAULT LogSeverity = 0
// (100) Debug or trace information.
LogSeverity_DEBUG LogSeverity = 100
// (200) Routine information, such as ongoing status or performance.
LogSeverity_INFO LogSeverity = 200
// (300) Normal but significant events, such as start up, shut down, or
// a configuration change.
LogSeverity_NOTICE LogSeverity = 300
// (400) Warning events might cause problems.
LogSeverity_WARNING LogSeverity = 400
// (500) Error events are likely to cause problems.
LogSeverity_ERROR LogSeverity = 500
// (600) Critical events cause more severe problems or outages.
LogSeverity_CRITICAL LogSeverity = 600
// (700) A person must take an action immediately.
LogSeverity_ALERT LogSeverity = 700
// (800) One or more systems are unusable.
LogSeverity_EMERGENCY LogSeverity = 800
)

确保你在Router Sink中设置了正确的JSON。

最新更新