forked from actions/actions-runner-controller
-
Notifications
You must be signed in to change notification settings - Fork 1
/
logger.go
90 lines (80 loc) · 2.19 KB
/
logger.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 logging
import (
"errors"
"fmt"
"os"
"strconv"
"time"
"github.com/go-logr/logr"
zaplib "go.uber.org/zap"
"go.uber.org/zap/zapcore"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
)
const (
LogLevelDebug = "debug"
LogLevelInfo = "info"
LogLevelWarn = "warn"
LogLevelError = "error"
LogFormatText = "text"
LogFormatJSON = "json"
)
var (
LogOpts = zap.Options{
TimeEncoder: zapcore.TimeEncoderOfLayout(time.RFC3339),
Development: true,
EncoderConfigOptions: []zap.EncoderConfigOption{
func(ec *zapcore.EncoderConfig) {
ec.LevelKey = "severity"
ec.MessageKey = "message"
},
},
}
)
func NewLogger(logLevel string, logFormat string) (logr.Logger, error) {
if !validLogFormat(logFormat) {
return logr.Logger{}, errors.New("invalid log format specified")
}
o := LogOpts
o.EncoderConfigOptions = make([]zap.EncoderConfigOption, len(LogOpts.EncoderConfigOptions))
copy(o.EncoderConfigOptions, LogOpts.EncoderConfigOptions)
if logFormat == "json" {
o.Development = false
o.TimeEncoder = nil
}
switch logLevel {
case LogLevelDebug:
lvl := zaplib.NewAtomicLevelAt(zaplib.DebugLevel) // maps to logr's V(1)
o.Level = &lvl
case LogLevelInfo:
lvl := zaplib.NewAtomicLevelAt(zaplib.InfoLevel)
o.Level = &lvl
case LogLevelWarn:
lvl := zaplib.NewAtomicLevelAt(zaplib.WarnLevel)
o.Level = &lvl
case LogLevelError:
lvl := zaplib.NewAtomicLevelAt(zaplib.ErrorLevel)
o.Level = &lvl
default:
// We use bitsize of 8 as zapcore.Level is a type alias to int8
levelInt, err := strconv.ParseInt(logLevel, 10, 8)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to parse --log-level=%s: %v", logLevel, err)
os.Exit(1)
}
// For example, --log-level=debug a.k.a --log-level=-1 maps to zaplib.DebugLevel, which is associated to logr's V(1)
// --log-level=-2 maps the specific custom log level that is associated to logr's V(2).
level := zapcore.Level(levelInt)
atomicLevel := zaplib.NewAtomicLevelAt(level)
o.Level = &atomicLevel
}
return zap.New(zap.UseFlagOptions(&o)), nil
}
func validLogFormat(logFormat string) bool {
validFormat := []string{"text", "json"}
for _, v := range validFormat {
if v == logFormat {
return true
}
}
return false
}