-
Notifications
You must be signed in to change notification settings - Fork 1
/
log.go
54 lines (50 loc) · 1.51 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
package main
import (
"fmt"
"github.com/go-logr/logr"
"github.com/go-logr/zapr"
"github.com/spf13/cobra"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"os"
"runtime"
"strings"
"time"
)
// LogMetadata prints various metadata to the root logger.
// It prints version, architecture and current user ID and returns nil.
func LogMetadata(cmd *cobra.Command) error {
log := logr.FromContextOrDiscard(cmd.Context())
log.WithValues(
"date", time.Now(),
"go_os", runtime.GOOS,
"go_arch", runtime.GOARCH,
"go_version", runtime.Version(),
"uid", os.Getuid(),
"gid", os.Getgid(),
).Info("Starting up " + cmd.Short)
return nil
}
func SetupLogging(cmd *cobra.Command, logLevel int, logFormat string) error {
isJson := strings.EqualFold("JSON", logFormat)
log, err := newZapLogger(strings.ToUpper(cmd.Use), logLevel, isJson)
cmd.SetContext(logr.NewContext(cmd.Context(), log))
return err
}
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)
return zlog, nil
}