-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
203 lines (180 loc) · 6 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
package xop
import (
"context"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"github.com/xoplog/xop-go/xopnum"
)
type contextKeyType struct{}
var contextKey = contextKeyType{}
// Default serves as a fallback logger if FromContextOrDefault
// does not find a logger. Unless modified, it discards all logs.
var Default = NewSeed().Request("discard")
func (logger *Logger) IntoContext(ctx context.Context) context.Context {
return context.WithValue(ctx, contextKey, logger)
}
func FromContext(ctx context.Context) (*Logger, bool) {
v := ctx.Value(contextKey)
if v == nil {
return nil, false
}
return v.(*Logger), true
}
func FromContextOrDefault(ctx context.Context) *Logger {
logger, ok := FromContext(ctx)
if ok {
return logger
}
return Default
}
func FromContextOrPanic(ctx context.Context) *Logger {
logger, ok := FromContext(ctx)
if !ok {
panic("Could not find logger in context")
}
return logger
}
// CustomFromContext returns a convenience function: it calls either
// FromContextOrPanic() or FromContextOrDefault() and then calls a
// function to adjust setting.
//
// Pass FromContextOrPanic or FromContextOrDefault as the first argument
// and a function to adjust settings as the second argument.
func CustomFromContext(getLogFromContext func(context.Context) *Logger, adjustSettings func(*Sub) *Sub) func(context.Context) *Logger {
return func(ctx context.Context) *Logger {
logger := getLogFromContext(ctx)
return adjustSettings(logger.Sub()).Logger()
}
}
// LevelAdjuster returns a function that adjusts the level of
// a logger for local package-scoped defaults. It is a sibling
// to AdjustedLevelLogger.
//
// The default behavior is to determine the name of the local
// package and then using that look at the environment variable
// "XOPLEVEL_<package_name>" (where <package_name> is the name of
// the current package) and set the minimum log level according
// to the value of that environment variable.
//
// package foo
// var adjustLogger = xop.LevelAdjuster()
func LevelAdjuster(opts ...AdjusterOption) func(*Logger) *Logger {
level := adjustConfig(opts)
if level == 0 {
return func(logger *Logger) *Logger { return logger }
}
return func(logger *Logger) *Logger {
return logger.Sub().MinLevel(level).Logger()
}
}
// ContextLevelAdjuster returns a function that gets a logger from
// context. The logger it returns will have a minimum logging level
// that is specific for the calling package. If starting from a logger
// instead of a context, use LevelAdjuster
//
// The level used will be the level set in this order:
// (1) From the environment variable "XOPLEVEL_foo" (for package foo). The level
// can either a string or the numeric level. See xopnum/level.go.
// (2) From the level provided in the call to AdjustedLevelLoger assuming that
// the passed level is not zero.
// (3) The level that the logger already has.
//
// package foo
// var getLogger = xop.AdjustedLevelLoger(xop.FromContextOrPanic)
func ContextLevelAdjuster(getLogFromContext func(context.Context) *Logger, opts ...AdjusterOption) func(context.Context) *Logger {
level := adjustConfig(opts)
if level == 0 {
return getLogFromContext
}
return CustomFromContext(getLogFromContext, func(sub *Sub) *Sub {
return sub.MinLevel(level)
})
}
// WithPackage overrides how the package name is found. The
// package name is combined with "XOPLEVEL_" to create the
// name of the environment variable to check for adjusting
// log levels with LevelAdjuster and ContextLevelAdjuster
func WithPackage(pkg string) AdjusterOption {
return func(o *adjustOptions) {
o.pkg = pkg
}
}
// WithEnvironment overrides the name of the environment variable
// used to override log levels in LevelAdjuster and ContextLevelAdjuster.
// WithEnvironment makes the package name irrelevant and thus should
// not bue used in combination with WithPackage.
func WithEnvironment(environmentVariableName string) AdjusterOption {
return func(o *adjustOptions) {
o.env = environmentVariableName
}
}
// WithDefault sets a default logger level for LevelAdjuster and
// ContextLevelAdjuster. If the environment variable is found then
// that will override this default. This default will override the
// existing minimum logging level.
//
// The default minimum level comes from DefaultSettings
func WithDefault(level xopnum.Level) AdjusterOption {
return func(o *adjustOptions) {
o.level = level
}
}
// WithSkippedFrames is needed only if LevelAdjuster or ContextLevelAdjuster
// are called from within another function that should not be used to
// derrive the package name.
func WithSkippedFrames(additionalFramesToSkip int) AdjusterOption {
return func(o *adjustOptions) {
o.skip = additionalFramesToSkip
}
}
type AdjusterOption func(*adjustOptions)
type adjustOptions struct {
pkg string
env string
level xopnum.Level
skip int
}
func adjustConfig(opts []AdjusterOption) xopnum.Level {
var options adjustOptions
for _, f := range opts {
f(&options)
}
pc := make([]uintptr, 1)
if options.pkg == "" && options.env == "" && runtime.Callers(3+options.skip, pc) > 0 {
frames := runtime.CallersFrames(pc)
frame, _ := frames.Next()
if frame.Function != "" {
// Example: github.com/xoplog/xop-go/xoptest/xoptestutil.foo.Context
// Example: github.com/xoplog/xop-go/xoptest/xoptestutil.TestAdjusterContext
// Example: github.com/xoplog/xop-go/xoptest/xoptestutil.init
base := filepath.Base(frame.Function)
parts := strings.SplitN(base, ".", 2)
if len(parts) == 2 {
options.pkg = parts[0]
}
}
if options.pkg == "" {
options.pkg = filepath.Base(filepath.Dir(frame.File))
if options.pkg == "." || options.pkg == "/" {
options.pkg = ""
}
}
}
if options.env == "" && options.pkg != "" {
options.env = "XOPLEVEL_" + options.pkg
}
if options.env != "" {
if ls, ok := os.LookupEnv(options.env); ok {
lvl, err := xopnum.LevelString(ls)
if err == nil {
options.level = lvl
} else if i, err := strconv.ParseInt(ls, 10, 64); err == nil {
options.level = xopnum.Level(i)
}
}
}
return options.level
}