This repository has been archived by the owner on May 14, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathlog.go
90 lines (77 loc) · 1.98 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
package main
import (
"fmt"
"io"
"os"
"sync"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/go-kit/kit/log/term"
)
// MultiLogger logs to multiple log.Logger instances on a single Log() call.
type MultiLogger struct {
log.Logger
loggers []log.Logger
}
// NewMultiLogger returns a new MultiLogger instance that logs to given loggers.
func NewMultiLogger(loggers ...log.Logger) *MultiLogger {
return &MultiLogger{
loggers: append([]log.Logger{}, loggers...),
}
}
// Log logs to all loggers.
func (l *MultiLogger) Log(keyvals ...interface{}) error {
kvs := keyvals[:len(keyvals):len(keyvals)]
if len(kvs)%2 != 0 {
kvs = append(kvs, log.ErrMissingValue)
}
var wg sync.WaitGroup
for _, l := range l.loggers {
wg.Add(1)
go func(l log.Logger) {
defer wg.Done()
l.Log(kvs...)
}(l)
}
wg.Wait()
return nil
}
// InitLoggers is a helper function that initializes two log.Logger instances,
// which log to stdout and a log file in JSON format.
func InitLoggers(logFile io.Writer, debug bool) log.Logger {
logfmt := term.NewLogger(log.NewSyncWriter(os.Stdout), log.NewLogfmtLogger, colorFn)
logjson := log.NewJSONLogger(log.NewSyncWriter(logFile))
var logger log.Logger
logger = NewMultiLogger(logfmt, logjson)
logger = log.With(logger, "timestamp", log.DefaultTimestampUTC)
if debug {
logger = level.NewFilter(logger, level.AllowDebug())
} else {
logger = level.NewFilter(logger, level.AllowInfo())
}
return logger
}
func colorFn(keyvals ...interface{}) term.FgBgColor {
for i := 0; i < len(keyvals)-1; i += 2 {
if keyvals[i] != "level" {
continue
}
s, ok := keyvals[i+1].(fmt.Stringer)
if !ok {
return term.FgBgColor{}
}
switch s.String() {
case "debug":
return term.FgBgColor{Fg: term.Gray}
case "info":
return term.FgBgColor{Fg: term.White}
case "warn":
return term.FgBgColor{Fg: term.Yellow}
case "error":
return term.FgBgColor{Fg: term.Red}
default:
return term.FgBgColor{}
}
}
return term.FgBgColor{}
}