-
Notifications
You must be signed in to change notification settings - Fork 0
/
log.go
70 lines (54 loc) · 1.27 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
package log
import (
"context"
"io"
"os"
"github.com/go-logr/logr"
)
type ctxValueType string
const (
logKey ctxValueType = "_logger"
)
// From extracts a logger from a context. If one does not exist, a new zap dev logger is created. This will panic if
// unable to create the zap dev logger.
func From(ctx context.Context) logr.Logger {
if ctx == nil {
return newLogger()
}
if logger, ok := ctx.Value(logKey).(logr.Logger); ok {
return logger
}
return newLogger()
}
func newLogger() logr.Logger {
l, err := ZapDevLogger()
if err != nil {
panic(err)
}
return l
}
// LoggerOption is an option for configuring the logger.
type LoggerOption func(config *LoggerConfig)
// LoggerOutput sets the output location for the logger.
func LoggerOutput(w io.Writer) LoggerOption {
if w == nil {
panic("logger output cannot be nil")
}
return func(config *LoggerConfig) {
config.out = w
}
}
// WithLogger creates a context with an existing logger.
func WithLogger(ctx context.Context, logger logr.Logger) context.Context {
return context.WithValue(ctx, logKey, logger)
}
// LoggerConfig is logger configuration.NewLogger
type LoggerConfig struct {
out io.Writer
}
func newLoggerConfig() *LoggerConfig {
config := &LoggerConfig{
out: os.Stderr,
}
return config
}