Skip to content

Instantly share code, notes, and snippets.

@memes
Last active August 7, 2023 18:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save memes/88c4145093982952d4e8b8bc2414f08f to your computer and use it in GitHub Desktop.
Save memes/88c4145093982952d4e8b8bc2414f08f to your computer and use it in GitHub Desktop.
go-logr and zerolog formatting for GCP stdout/stderr scraping
func initialiseLogging() logr.Logger {
// Setup structured logging to match Cloud Operations expectations, as much as possible
zerolog.TimestampFieldName = "time"
zerolog.TimeFieldFormat = time.RFC3339
zerolog.LevelFieldName = "severity"
zerolog.LevelTraceValue = "DEFAULT"
zerolog.LevelDebugValue = "DEBUG"
zerolog.LevelInfoValue = "INFO"
zerolog.LevelWarnValue = "WARNING"
zerolog.LevelErrorValue = "ERROR"
zerolog.LevelFatalValue = "CRITICAL"
zerolog.LevelPanicValue = "ALERT"
zerolog.MessageFieldName = "message"
zerolog.ErrorStackFieldName = "stack_trace" //nolint:reassign // This is not a sentinel error, just the name of a field
// There isn't a good way to change caller info into an embedded struct
// expected by Cloud Operations, so don't try.
// See https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#LogEntrySourceLocation
// and https://github.com/rs/zerolog/issues/472
// zerolog.CallerFieldName = "logging.googleapis.com/sourceLocation"
// zerolog.CallerMarshalFunc = func(_ uintptr, file string, line int) string {
// ...
// }
if os.Getenv("DEBUG") == "" {
zerolog.SetGlobalLevel(zerolog.InfoLevel)
} else {
zerolog.SetGlobalLevel(zerolog.TraceLevel)
}
zl := zerolog.New(os.Stdout).With().Caller().Timestamp().Logger()
return zerologr.New(&zl)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment