-
Notifications
You must be signed in to change notification settings - Fork 0
/
log.go
463 lines (411 loc) · 12.6 KB
/
log.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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
/*
Copyright 2018 Cai Gwatkin
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package log
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
"reflect"
"runtime"
"strings"
"time"
go_context "github.com/caigwatkin/go/context"
go_environment "github.com/caigwatkin/go/environment"
)
type Client interface {
Debug(ctx context.Context, message string, fields ...Field)
Info(ctx context.Context, message string, fields ...Field)
Notice(ctx context.Context, message string, fields ...Field)
Warn(ctx context.Context, message string, fields ...Field)
Error(ctx context.Context, message string, fields ...Field)
Fatal(ctx context.Context, message string, fields ...Field)
}
var (
remote bool
)
type Config struct {
Env go_environment.Environment
}
// NewClient for logging
func NewClient(ctx context.Context, config Config) Client {
fmt.Println("Initializing", config)
remote = config.Env.Remote
flag := 0
colorCyan := ""
colorGreen := ""
colorRed := ""
colorYellow := ""
if !remote {
flag = log.Ldate | log.Ltime | log.Lmicroseconds
colorCyan = fmt.Sprintf("\x1b[%dm", cyan)
colorGreen = fmt.Sprintf("\x1b[%dm", green)
colorRed = fmt.Sprintf("\x1b[%dm", red)
colorYellow = fmt.Sprintf("\x1b[%dm", yellow)
}
c := client{
config: config,
loggerDebug: log.New(os.Stdout, fmt.Sprintf("%sDEBUG ", colorGreen), flag),
loggerInfo: log.New(os.Stdout, fmt.Sprintf("%sINFO ", colorCyan), flag),
loggerWarn: log.New(os.Stderr, fmt.Sprintf("%sWARN ", colorYellow), flag),
loggerError: log.New(os.Stderr, fmt.Sprintf("%sERROR ", colorRed), flag),
loggerFatal: log.New(os.Stderr, fmt.Sprintf("%sFATAL ", colorRed), flag),
}
c.Info(ctx, "Initialized", FmtAny(config, "config"))
return c
}
type client struct {
config Config
loggerDebug *log.Logger
loggerInfo *log.Logger
loggerWarn *log.Logger
loggerError *log.Logger
loggerFatal *log.Logger
}
// Debug log at debug level
func (c client) Debug(ctx context.Context, message string, fields ...Field) {
if c.config.Env.Debug {
c.output(ctx, severityDebug, message, fields)
}
}
// Info log at info level
func (c client) Info(ctx context.Context, message string, fields ...Field) {
c.output(ctx, severityInfo, message, fields)
}
// Notice log at notice level
func (c client) Notice(ctx context.Context, message string, fields ...Field) {
c.output(ctx, severityNotice, message, fields)
}
// Warn log at warn level
func (c client) Warn(ctx context.Context, message string, fields ...Field) {
c.output(ctx, severityWarn, message, fields)
}
// Error log at error level
func (c client) Error(ctx context.Context, message string, fields ...Field) {
c.output(ctx, severityError, message, fields)
}
// Fatal log at fatal level
func (c client) Fatal(ctx context.Context, message string, fields ...Field) {
c.output(ctx, severityFatal, message, fields)
}
// Field to log
type Field string
// FmtAny using JSON marshaller with indenting
//
// Use this to format for logging any object that can be JSON unmarshalled
// Type and value will be logged
// If JSON unmarshalling fails, the value will not be logged
func FmtAny(value interface{}, name string) Field {
if remote {
if value == nil {
return Field(fmt.Sprintf("%q:null", name))
}
blob, err := json.Marshal(value)
if err != nil {
return Field(fmt.Sprintf("%q:{\"type\":%q,\"value\":\"NOT JSON MARSHALLABLE\"}", name, reflect.TypeOf(value)))
}
return Field(fmt.Sprintf("%q:{\"type\":%q,\"value\":%s}", name, reflect.TypeOf(value), blob))
}
if value == nil {
return Field(fmt.Sprintf("%q: null", name))
}
blob, err := json.MarshalIndent(value, "\t\t", "\t")
if err != nil {
return Field(fmt.Sprintf("%q: {\n\t\t\"type\": %q,\n\t\t\"value\": \"NOT JSON MARSHALLABLE\"\n\t}", name, reflect.TypeOf(value)))
}
return Field(fmt.Sprintf("%q: {\n\t\t\"type\": %q,\n\t\t\"value\": %s\n\t}", name, reflect.TypeOf(value), blob))
}
// FmtAnys using JSON marshaller with indenting
//
// Use this to format for logging any object that can be JSON unmarshalled
// Type and value will be logged
// If JSON unmarshalling fails, the value will not be logged
func FmtAnys(values []interface{}, name string) Field {
if remote {
var vals []interface{}
for _, v := range values {
if v == nil {
vals = append(vals, "null")
continue
}
var s string
if blob, err := json.Marshal(v); err != nil {
s = fmt.Sprintf("{\"type\":%q,\"value\":\"NOT JSON MARSHALLABLE\"}", reflect.TypeOf(v))
} else {
s = fmt.Sprintf("{\"type\":%q,\"value\":%s}", reflect.TypeOf(v), blob)
}
vals = append(vals, s)
}
return fmtSlice(vals, name, "%s")
}
var vals []interface{}
for _, v := range values {
if v == nil {
vals = append(vals, "null")
continue
}
var s string
if blob, err := json.MarshalIndent(v, "\t\t\t", "\t"); err != nil {
s = fmt.Sprintf("{\n\t\t\t\"type\": %q,\n\t\t\t\"value\": \"NOT JSON MARSHALLABLE\"\n\t\t}", reflect.TypeOf(v))
} else {
s = fmt.Sprintf("{\n\t\t\t\"type\": %q,\n\t\t\t\"value\": %s\n\t\t}", reflect.TypeOf(v), blob)
}
vals = append(vals, s)
}
return fmtSlice(vals, name, "%s")
}
// FmtBool as name/value pair for logging
func FmtBool(value bool, name string) Field {
if remote {
return Field(fmt.Sprintf("%q:%t", name, value))
}
return Field(fmt.Sprintf("%q: %t", name, value))
}
// FmtBools as name/[values] pair for logging
func FmtBools(values []bool, name string) Field {
var vals []interface{}
for _, v := range values {
vals = append(vals, v)
}
return fmtSlice(vals, name, "%t")
}
// FmtByte as name/value pair for logging
func FmtByte(value byte, name string) Field {
if remote {
return Field(fmt.Sprintf("%q:%q", name, value))
}
return Field(fmt.Sprintf("%q: %q", name, value))
}
// FmtBytes as name/value pair for logging
func FmtBytes(value []byte, name string) Field {
if remote {
return Field(fmt.Sprintf("%q:%q", name, value))
}
return Field(fmt.Sprintf("%q: %q", name, value))
}
// FmtDuration as name/value pair for logging
func FmtDuration(value time.Duration, name string) Field {
if remote {
return Field(fmt.Sprintf("%q:%q", name, value))
}
return Field(fmt.Sprintf("%q: %q", name, value))
}
// FmtDurations as name/[values] pair for logging
func FmtDurations(values []time.Duration, name string) Field {
var vals []interface{}
for _, v := range values {
vals = append(vals, v)
}
return fmtSlice(vals, name, "%q")
}
// FmtError as name/value pair for logging
func FmtError(err error) Field {
if remote {
if err == nil {
return Field("\"error\":null")
}
friendly := fmt.Sprintf("%s", err)
trace := fmt.Sprintf("%+v", err)
if trace == friendly {
return Field(fmt.Sprintf("\"error\":%q", friendly))
}
return Field(fmt.Sprintf("\"error\":{\"friendly\":%q,\"trace\":%s}", friendly, trace))
}
if err == nil {
return Field("\"error\": null")
}
friendly := fmt.Sprintf("%s", err)
trace := fmt.Sprintf("%+v", err)
if trace == friendly {
return Field(fmt.Sprintf("\"error\": %q", friendly))
}
return Field(fmt.Sprintf("\"error\": {\n\t\t\"friendly\": %q,\n\t\t\"trace\": %s\n\t}", friendly, trace))
}
// FmtFloat32 as name/value pair for logging
func FmtFloat32(value float32, name string) Field {
if remote {
return Field(fmt.Sprintf("%q:%.5f", name, value))
}
return Field(fmt.Sprintf("%q: %.5f", name, value))
}
// FmtFloat32s as name/[values] pair for logging
func FmtFloat32s(values []float32, name string) Field {
var vals []interface{}
for _, v := range values {
vals = append(vals, v)
}
return fmtSlice(vals, name, "%.5f")
}
// FmtFloat64 as name/value pair for logging
func FmtFloat64(value float64, name string) Field {
if remote {
return Field(fmt.Sprintf("%q:%.10f", name, value))
}
return Field(fmt.Sprintf("%q: %.10f", name, value))
}
// FmtFloat64s as name/[values] pair for logging
func FmtFloat64s(values []float64, name string) Field {
var vals []interface{}
for _, v := range values {
vals = append(vals, v)
}
return fmtSlice(vals, name, "%.10f")
}
// FmtInt as name/value pair for logging
func FmtInt(value int, name string) Field {
if remote {
return Field(fmt.Sprintf("%q:%d", name, value))
}
return Field(fmt.Sprintf("%q: %d", name, value))
}
// FmtInts as name/[values] pair for logging
func FmtInts(values []int, name string) Field {
var vals []interface{}
for _, v := range values {
vals = append(vals, v)
}
return fmtSlice(vals, name, "%d")
}
// FmtInt32 as name/value pair for logging
func FmtInt32(value int32, name string) Field {
if remote {
return Field(fmt.Sprintf("%q:%d", name, value))
}
return Field(fmt.Sprintf("%q: %d", name, value))
}
// FmtInt32s as name/[values] pair for logging
func FmtInt32s(values []int32, name string) Field {
var vals []interface{}
for _, v := range values {
vals = append(vals, v)
}
return fmtSlice(vals, name, "%d")
}
// FmtInt64 as name/value pair for logging
func FmtInt64(value int64, name string) Field {
if remote {
return Field(fmt.Sprintf("%q:%d", name, value))
}
return Field(fmt.Sprintf("%q: %d", name, value))
}
// FmtInt64s as name/[values] pair for logging
func FmtInt64s(values []int64, name string) Field {
var vals []interface{}
for _, v := range values {
vals = append(vals, v)
}
return fmtSlice(vals, name, "%d")
}
// FmtString as name/value pair for logging
func FmtString(value string, name string) Field {
if remote {
return Field(fmt.Sprintf("%q:%q", name, value))
}
return Field(fmt.Sprintf("%q: %q", name, value))
}
// FmtStrings as name/[values] pair for logging
func FmtStrings(values []string, name string) Field {
var vals []interface{}
for _, v := range values {
vals = append(vals, v)
}
return fmtSlice(vals, name, "%q")
}
// FmtTime as name/value pair for logging
func FmtTime(value time.Time, name string) Field {
if remote {
return Field(fmt.Sprintf("%q:%q", name, value.Format(time.RFC3339Nano)))
}
return Field(fmt.Sprintf("%q: %q", name, value.Format(time.RFC3339Nano)))
}
// FmtTimes as name/[values] pair for logging
func FmtTimes(values []time.Time, name string) Field {
var vals []interface{}
for _, v := range values {
vals = append(vals, v.Format(time.RFC3339Nano))
}
return fmtSlice(vals, name, "%q")
}
func fmtSlice(values []interface{}, name, format string) Field {
if remote {
if len(values) == 0 {
return Field(fmt.Sprintf("%q:[]", name))
}
f := make([]string, len(values))
for i, v := range values {
f[i] = fmt.Sprintf(format, v)
}
return Field(fmt.Sprintf("%q:[%s]", name, strings.Join(f, ",")))
}
if len(values) == 0 {
return Field(fmt.Sprintf("%q: []", name))
}
f := make([]string, len(values))
for i, v := range values {
f[i] = fmt.Sprintf(format, v)
}
return Field(fmt.Sprintf("%q: [\n\t\t%s\n\t]", name, strings.Join(f, ",\n\t\t")))
}
const (
red = 31
green = 32
yellow = 33
cyan = 36
severityDebug = iota
severityInfo = iota
severityNotice = iota // Flush, if applicable
severityWarn = iota
severityError = iota
severityFatal = iota // Flush, if applicable
)
func (c client) output(ctx context.Context, severity int, message string, fields []Field) {
line, funcName := runtimeLineAndFuncName(2)
message = fmtLog(message, go_context.CorrelationId(ctx), funcName, line, fields)
switch severity {
case severityDebug:
c.loggerDebug.Println(message)
case severityInfo, severityNotice:
c.loggerInfo.Println(message)
case severityWarn:
c.loggerWarn.Println(message)
case severityError:
c.loggerError.Println(message)
case severityFatal:
c.loggerFatal.Panicln(message)
}
}
func runtimeLineAndFuncName(skip int) (int, string) {
pc, _, line, _ := runtime.Caller(skip + 1)
funcName := runtime.FuncForPC(pc).Name()
return line, funcName
}
func fmtLog(message, correlationId, funcName string, line int, fields []Field) string {
if remote {
return fmt.Sprintf("[%s] [%s] [%s:%d] %s", message, correlationId, funcName, line, fmtFields(fields))
}
return fmt.Sprintf("[%s] [%s] [%s:%d] %s\x1b[0m", message, correlationId, funcName, line, fmtFields(fields))
}
func fmtFields(fields []Field) string {
if len(fields) == 0 {
return ""
}
var fs []string
for _, field := range fields {
fs = append(fs, string(field))
}
if remote {
return fmt.Sprintf("{%s}", strings.Join(fs, ","))
}
return fmt.Sprintf("{\n\t%s\n}", strings.Join(fs, ",\n\t"))
}