-
Notifications
You must be signed in to change notification settings - Fork 188
/
logginghelpers.go
80 lines (69 loc) · 1.97 KB
/
logginghelpers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package utility
import (
"context"
"fmt"
"log"
"os"
"runtime/debug"
"cloud.google.com/go/logging"
)
// CreateLoggerWrapper creates and initializes the LoggerWrapper,
// and also returns a cleanup function to be deferred
func CreateLoggerWrapper(logID string) (LoggerWrapper, func()) {
projectId, projectIdSet := os.LookupEnv("GOOGLE_CLOUD_PROJECT")
if !projectIdSet {
return LoggerWrapper{}, func() {}
}
log.Println("Logging to project id: " + projectId)
client, err := logging.NewClient(context.Background(), projectId)
if err != nil {
log.Fatalf("Failed to create client: %v", err)
}
wrapper := LoggerWrapper{
GCloudLogger: client.Logger(logID),
}
return wrapper, func() { client.Close() }
}
// LoggerWrapper wraps the Logger provided by google cloud
// Will default to the go stdout and stderr logging if GCP logger is not set
type LoggerWrapper struct {
GCloudLogger *logging.Logger
}
// Infof prints Info level log
func (wrapper LoggerWrapper) Infof(format string, a ...any) {
if wrapper.GCloudLogger == nil {
log.Printf(format, a...)
return
}
wrapper.GCloudLogger.Log(logging.Entry{
Severity: logging.Info,
Payload: fmt.Sprintf(format, a...) + "\n",
})
}
// Warnf prints Warning level log, defaults to stdout if GCP logger is not set
func (wrapper LoggerWrapper) Warnf(format string, a ...any) {
if wrapper.GCloudLogger == nil {
log.Printf(format, a...)
return
}
wrapper.GCloudLogger.Log(logging.Entry{
Severity: logging.Warning,
Payload: fmt.Sprintf(format, a...) + "\n",
})
}
// Fatalf prints Error level log with stack trace, before exiting with error code 1
func (wrapper LoggerWrapper) Fatalf(format string, a ...any) {
if wrapper.GCloudLogger == nil {
log.Fatalf(format, a...)
return
}
wrapper.GCloudLogger.Log(logging.Entry{
Severity: logging.Error,
Payload: fmt.Sprintf(format, a...) + "\n" + string(debug.Stack()),
})
err := wrapper.GCloudLogger.Flush()
if err != nil {
log.Fatalln("Failed to flush logger")
}
os.Exit(1)
}