-
Notifications
You must be signed in to change notification settings - Fork 1
/
context.go
85 lines (70 loc) · 1.43 KB
/
context.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
// Copyright 2021, The Go Authors. All rights reserved.
// Author: crochee
// Date: 2021/1/17
package logger
import (
"context"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
type Option interface {
Apply(*Logger)
}
type Level string
func (l Level) Apply(log *Logger) {
if log == nil {
return
}
if coreLevel, ok := map[Level]zapcore.Level{
DebugLevel: zap.DebugLevel,
InfoLevel: zap.InfoLevel,
WarnLevel: zap.WarnLevel,
ErrorLevel: zap.ErrorLevel,
DpanicLevel: zap.DPanicLevel,
PanicLevel: zap.PanicLevel,
FatalLevel: zap.FatalLevel,
}[l]; ok {
log.level = coreLevel
return
}
log.level = zap.InfoLevel
}
const (
DebugLevel Level = "DEBUG"
InfoLevel Level = "INFO"
WarnLevel Level = "WARN"
ErrorLevel Level = "ERROR"
DpanicLevel Level = "DPANIC"
PanicLevel Level = "PANIC"
FatalLevel Level = "FATAL"
)
type LogPath string
func (l LogPath) Apply(log *Logger) {
if log == nil {
return
}
log.path = string(l)
}
type Enable bool
func (e Enable) Apply(log *Logger) {
if !e {
log = (*Logger)(nil)
}
}
type loggerKey struct{}
// With Adds fields.
func With(ctx context.Context, opts ...Option) context.Context {
InitLogger(opts...)
return context.WithValue(ctx, loggerKey{}, logger)
}
// FromContext Gets the logger from context.
func FromContext(ctx context.Context) *Logger {
if ctx == nil {
return nil
}
l, ok := ctx.Value(loggerKey{}).(*Logger)
if !ok {
return nil
}
return l
}