Reputation: 31
I created a Logs Router Sink to export logs to a Pub/Sub. My Golang application is supposed to consume messages from this Pub/Sub via a dedicated Subscription using google client library (Golang).
The messages received on the Subscription are JSON representations of LogEntry objects.
The question: How to unmarshal the JSONs into useful Golang objects?
textPayload
JSON field was not unmarshalledcannot unmarshal string into Go struct field LogEntry.severity of type ltype.LogSeverity
Upvotes: 3
Views: 847
Reputation: 15767
If you get errors about protoPayload
or timestamppb.Timestamp
it probably is a JSON representation of a protocol buffer. To Marshall/Unmarshal protocol buffers in Go you should use the protojson package. Example:
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)
}
Upvotes: 1
Reputation: 179
JSON you are trying to parse contains string instead of an integer. The Log severity code should be one of these:
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
)
Make sure you are setting the correct JSON in Router Sink.
Upvotes: 0