-
Notifications
You must be signed in to change notification settings - Fork 1
/
logging.go
284 lines (241 loc) · 8.28 KB
/
logging.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package foundation
import (
stdlog "log"
"os"
"strings"
"sync/atomic"
"github.com/google/uuid"
"github.com/logrusorgru/aurora"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
const (
// LogFormatPlainText outputs logs in plain text without colorization and with timestamp; is the default if log format isn't specified
LogFormatPlainText = "plaintext"
// LogFormatConsole outputs logs in plain text with colorization and without timestamp
LogFormatConsole = "console"
// LogFormatJSON outputs logs in json including appgroup, app, appversion and other metadata
LogFormatJSON = "json"
// LogFormatStackdriver outputs a format similar to JSON format but with 'severity' instead of 'level' field
LogFormatStackdriver = "stackdriver"
// LogFormatV3 ouputs an internal format used at Travix in JSON format with nested payload and a specific set of required metadata
LogFormatV3 = "v3"
)
// InitLoggingFromEnv initalializes a logger with format specified in envvar ESTAFETTE_LOG_FORMAT and outputs a startup message
func InitLoggingFromEnv(applicationInfo ApplicationInfo) {
InitLoggingByFormat(applicationInfo, os.Getenv("ESTAFETTE_LOG_FORMAT"))
}
// InitLoggingByFormat initalializes a logger with specified format and outputs a startup message
func InitLoggingByFormat(applicationInfo ApplicationInfo, logFormat string) {
// configure logger
InitLoggingByFormatSilent(applicationInfo, logFormat)
// set global logging level
SetLoggingLevelFromEnv()
// output startup message
switch logFormat {
case LogFormatV3:
logStartupMessageV3(applicationInfo)
default:
logStartupMessage(applicationInfo)
}
}
// InitLoggingByFormatSilent initializes a logger with specified format without outputting a startup message
func InitLoggingByFormatSilent(applicationInfo ApplicationInfo, logFormat string) {
// configure logger
switch logFormat {
case LogFormatJSON:
initLoggingJSON(applicationInfo)
case LogFormatStackdriver:
initLoggingStackdriver(applicationInfo)
case LogFormatV3:
initLoggingV3(applicationInfo)
case LogFormatConsole:
initLoggingConsole(applicationInfo)
default: // LogFormatPlainText
initLoggingPlainText(applicationInfo)
}
}
// SetLoggingLevelFromEnv sets the logging level from which log messages and higher are outputted via envvar ESTAFETTE_LOG_LEVEL
func SetLoggingLevelFromEnv() {
logLevel := os.Getenv("ESTAFETTE_LOG_LEVEL")
switch strings.ToLower(logLevel) {
case "disabled":
zerolog.SetGlobalLevel(zerolog.Disabled)
case "trace":
zerolog.SetGlobalLevel(zerolog.TraceLevel)
case "debug":
zerolog.SetGlobalLevel(zerolog.DebugLevel)
case "info":
zerolog.SetGlobalLevel(zerolog.InfoLevel)
case "warn":
zerolog.SetGlobalLevel(zerolog.WarnLevel)
case "error":
zerolog.SetGlobalLevel(zerolog.ErrorLevel)
case "fatal":
zerolog.SetGlobalLevel(zerolog.FatalLevel)
case "panic":
zerolog.SetGlobalLevel(zerolog.PanicLevel)
}
}
// initLoggingStackdriver outputs a format similar to JSON format but with 'severity' instead of 'level' field
func initLoggingStackdriver(applicationInfo ApplicationInfo) {
zerolog.TimeFieldFormat = "2006-01-02T15:04:05.999Z"
zerolog.TimestampFieldName = "timestamp"
zerolog.LevelFieldName = "severity"
// set some default fields added to all logs
log.Logger = zerolog.New(os.Stdout).With().
Timestamp().
Logger()
// use zerolog for any logs sent via standard log library
stdlog.SetFlags(0)
stdlog.SetOutput(log.Logger)
}
// initLoggingJSON outputs logs in json including appgroup, app, appversion and other metadata
func initLoggingJSON(applicationInfo ApplicationInfo) {
// set some default fields added to all logs
log.Logger = zerolog.New(os.Stdout).With().
Timestamp().
Logger()
// use zerolog for any logs sent via standard log library
stdlog.SetFlags(0)
stdlog.SetOutput(log.Logger)
}
// initLoggingConsole outputs logs in plain text with colorization and without timestamp
func initLoggingConsole(applicationInfo ApplicationInfo) {
output := zerolog.ConsoleWriter{
Out: os.Stdout,
NoColor: false,
}
output.FormatTimestamp = func(i interface{}) string {
return ""
}
output.FormatCaller = func(i interface{}) string {
return ""
}
output.FormatLevel = func(i interface{}) string {
return ""
}
log.Logger = zerolog.New(output).With().Logger()
// use zerolog for any logs sent via standard log library
stdlog.SetFlags(0)
stdlog.SetOutput(log.Logger)
}
// initLoggingPlainText outputs logs in plain text without colorization and with timestamp; is the default if log format isn't specified
func initLoggingPlainText(applicationInfo ApplicationInfo) {
output := zerolog.ConsoleWriter{
Out: os.Stdout,
NoColor: true,
}
log.Logger = zerolog.New(output).With().Logger()
// use zerolog for any logs sent via standard log library
stdlog.SetFlags(0)
stdlog.SetOutput(log.Logger)
}
var (
sequenceID uint64
)
type v3Error struct {
Message string `json:"message"`
}
type messageIDHook struct{}
func (h messageIDHook) Run(e *zerolog.Event, level zerolog.Level, msg string) {
e.Str("messageuniqueid", uuid.New().String())
e.Uint64("sequenceid", atomic.AddUint64(&sequenceID, 1))
}
// initLoggingV3 ouputs an internal format used at Travix in JSON format with nested payload and a specific set of required metadata
func initLoggingV3(applicationInfo ApplicationInfo) {
zerolog.TimeFieldFormat = "2006-01-02T15:04:05.999Z"
zerolog.TimestampFieldName = "timestamp"
zerolog.LevelFieldName = "loglevel"
zerolog.LevelFieldMarshalFunc = func(l zerolog.Level) string {
switch l {
case zerolog.DebugLevel:
return "DEBUG"
case zerolog.InfoLevel:
return "INFO"
case zerolog.WarnLevel:
return "WARN"
case zerolog.ErrorLevel:
return "ERROR"
case zerolog.FatalLevel:
return "FATAL"
case zerolog.PanicLevel:
return "PANIC"
case zerolog.NoLevel:
return ""
}
return ""
}
hostname, err := os.Hostname()
if err != nil {
hostname = "unknown"
}
source := struct {
AppGroup string `json:"appgroup"`
AppName string `json:"appname"`
AppVersion string `json:"appversion"`
Hostname string `json:"hostname"`
}{
applicationInfo.AppGroup,
applicationInfo.App,
applicationInfo.Version,
hostname,
}
// set some default fields added to all logs
log.Logger = zerolog.New(os.Stdout).Hook(messageIDHook{}).With().
Timestamp().
Str("logformat", "v3").
Str("messagetype", "estafette").
Str("messagetypeversion", "0.0.0").
Interface("source", source).
Logger()
// Have the error message under and object in "error" instead of in a raw string.
zerolog.ErrorMarshalFunc = func(err error) interface{} {
if err == nil {
return nil
}
return v3Error{err.Error()}
}
// use zerolog for any logs sent via standard log library
stdlog.SetFlags(0)
stdlog.SetOutput(log.Logger)
}
// logStartupMessage logs a default startup message for any Estafette application
func logStartupMessage(applicationInfo ApplicationInfo) {
log.Info().
Str("branch", applicationInfo.Branch).
Str("revision", applicationInfo.Revision).
Str("buildDate", applicationInfo.BuildDate).
Str("goVersion", applicationInfo.GoVersion()).
Str("os", applicationInfo.OperatingSystem()).
Msgf("Starting %v version %v...", applicationInfo.App, applicationInfo.Version)
}
// logStartupMessageConsole logs a default startup message for any Estafette application in bold
func logStartupMessageConsole(applicationInfo ApplicationInfo) {
log.Info().
Str("branch", applicationInfo.Branch).
Str("revision", applicationInfo.Revision).
Str("buildDate", applicationInfo.BuildDate).
Str("goVersion", applicationInfo.GoVersion()).
Str("os", applicationInfo.OperatingSystem()).
Msg(aurora.Sprintf("Starting %v version %v...", aurora.Bold(applicationInfo.App), aurora.Bold(applicationInfo.Version)))
}
// logStartupMessageV3 logs a v3 startup message for any Estafette application
func logStartupMessageV3(applicationInfo ApplicationInfo) {
startupProps := struct {
Branch string `json:"branch"`
Revision string `json:"revision"`
BuildDate string `json:"buildDate"`
GoVersion string `json:"goVersion"`
Os string `json:"os"`
}{
applicationInfo.Branch,
applicationInfo.Revision,
applicationInfo.BuildDate,
applicationInfo.GoVersion(),
applicationInfo.OperatingSystem(),
}
log.Info().
Interface("payload", startupProps).
Msgf("Starting %v version %v...", applicationInfo.App, applicationInfo.Version)
}