-
Notifications
You must be signed in to change notification settings - Fork 3
/
logger.go
68 lines (61 loc) · 1.9 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
package main
import (
"fmt"
"os"
"runtime"
"strings"
"github.com/go-logr/logr"
"github.com/go-logr/zapr"
"github.com/urfave/cli/v2"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
func init() {
// Remove `-v` short option from --version flag
cli.VersionFlag.(*cli.BoolFlag).Aliases = nil
}
// LogMetadata prints various metadata to the root logger.
// It prints version, architecture and current user ID and returns nil.
func LogMetadata(c *cli.Context) error {
log := logr.FromContextOrDiscard(c.Context)
log.WithValues(
"version", version,
"date", date,
"commit", commit,
"go_os", runtime.GOOS,
"go_arch", runtime.GOARCH,
"go_version", runtime.Version(),
"uid", os.Getuid(),
"gid", os.Getgid(),
).Info("Starting up " + appName)
return nil
}
func setupLogging(c *cli.Context) error {
log, err := newZapLogger(appName, c.Int(newLogLevelFlag().Name), usesProductionLoggingConfig(c))
c.Context = logr.NewContext(c.Context, log)
return err
}
func usesProductionLoggingConfig(c *cli.Context) bool {
return strings.EqualFold("JSON", c.String(newLogFormatFlag().Name))
}
func newZapLogger(name string, verbosityLevel int, useProductionConfig bool) (logr.Logger, error) {
cfg := zap.NewDevelopmentConfig()
cfg.EncoderConfig.ConsoleSeparator = " | "
if useProductionConfig {
cfg = zap.NewProductionConfig()
}
// Zap's levels get more verbose as the number gets smaller,
// bug logr's level increases with greater numbers.
cfg.Level = zap.NewAtomicLevelAt(zapcore.Level(verbosityLevel * -1))
z, err := cfg.Build()
if err != nil {
return logr.Discard(), fmt.Errorf("error configuring the logging stack: %w", err)
}
zap.ReplaceGlobals(z)
zlog := zapr.NewLogger(z).WithName(name)
if useProductionConfig {
// Append the version to each log so that logging stacks like EFK/Loki can correlate errors with specific versions.
return zlog.WithValues("version", version), nil
}
return zlog, nil
}