Skip to content

Commit

Permalink
Logging an error instead of truncating the message
Browse files Browse the repository at this point in the history
Because the other logic didn't have a good way of checking the size of
the object you where potentially trying to serialize into the log.
  • Loading branch information
karl-gustav committed Mar 5, 2022
1 parent 6bf7e32 commit ff4aa7e
Showing 1 changed file with 15 additions and 8 deletions.
23 changes: 15 additions & 8 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const (
emergency_severety severety = "EMERGENCY" // One or more systems are unusable.)
)

const trunkateMessage = "[message over 100Kb, truncating]..."
const maxSize = 102400

type Logger struct{}

Expand Down Expand Up @@ -150,10 +150,16 @@ func (l *Logger) writeLog(severety severety, message string) {
Line: strconv.Itoa(line),
},
}
err := json.NewEncoder(os.Stdout).Encode(payload)
j, err := json.Marshal(payload)
if err != nil {
panic("could not log TextPayload because of err: " + err.Error())
}

if len(j) >= maxSize {
l.Errorf("log entry exeed max size of %d bytes: %.100000s", maxSize, j)
} else {
os.Stdout.Write(j)
}
}

func (l *Logger) writeJson(severety severety, message string, obj interface{}) {
Expand All @@ -164,11 +170,6 @@ func (l *Logger) writeJson(severety severety, message string, obj interface{}) {
return
}

// GCP has max 102400 bytes limit, so setting 100k for message and 2.4k for other fields
if len(message) > 100000 {
message = message[0:100000-len(trunkateMessage)] + trunkateMessage
}

payload := &stackdriverLogStruct{
JsonPayload: obj,
TextPayload: message,
Expand All @@ -180,10 +181,16 @@ func (l *Logger) writeJson(severety severety, message string, obj interface{}) {
Line: strconv.Itoa(line),
},
}
err := json.NewEncoder(os.Stdout).Encode(payload)
j, err := json.Marshal(payload)
if err != nil {
panic("could not log JsonPayload because of err: " + err.Error())
}

if len(j) >= maxSize {
l.Errorf("log entry exeed max size of %d bytes: %.100000s", maxSize, j)
} else {
os.Stdout.Write(j)
}
}

// stackdriverLogStruct source https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry
Expand Down

0 comments on commit ff4aa7e

Please sign in to comment.