Repository navigation
Expand file tree
/
Copy pathhandler.go
More file actions
253 lines (211 loc) · 6.43 KB
/
Copy pathhandler.go
File metadata and controls
253 lines (211 loc) · 6.43 KB
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
package slogscope
import (
"context"
"fmt"
"log/slog"
"regexp"
"runtime"
"strconv"
"strings"
"time"
)
var logLevelRegex = regexp.MustCompile(`([a-zA-Z]+)(([+\-])(\d+))?`)
type Handler struct {
*slogscope
}
// NewHandler creates a new slog.Handler
func NewHandler(h slog.Handler, opts *HandlerOptions) *Handler {
o := HandlerOptions{}
if opts != nil {
o = *opts
}
if o.ConfigFile == "" {
o.ConfigFile = defaultConfigFile
}
var logger *slog.Logger
switch h.(type) {
case nil:
panic("slog.Handler must not be nil")
case *Handler:
panic("slog.Handler must not be of type *Handler")
default:
ih := &internalHandler{h: h, debug: o.Debug}
logger = slog.New(ih).WithGroup("slogscope").With(slog.Attr{
Key: "version",
Value: slog.StringValue(version),
})
if o.Debug {
logger.Debug("debug mode enabled")
}
}
ss := &slogscope{logger: logger, slogh: h, opts: &o}
defer ss.initHandler()
// We load the HandlerOptions.Config from a config file if no HandlerOptions.Config is provided.
if ss.opts.Config == nil && ss.opts.ConfigFile != "" {
ss.loadConfig()
}
ssHndl := &Handler{
slogscope: ss,
}
ssHndl.h = ssHndl
return ssHndl
}
func (h *Handler) Enabled(_ context.Context, lvl slog.Level) bool {
var pcs [12]uintptr
// Skip 2: skip runtime.Callers and Handler.Enabled
n := runtime.Callers(2, pcs[:])
var info callSiteInfo
var resolved bool
for i := 0; i < n; i++ {
siteInfo := h.resolveCallSite(pcs[i])
if siteInfo.pkgName != "log/slog" && siteInfo.pkgName != "runtime" {
info = siteInfo
resolved = true
break
}
}
if !resolved {
return lvl >= slog.Level(h.logLvl.Load())
}
if info.hasOverride {
if lvl >= info.overrideLvl {
if h.debug.Load() {
h.logger.Debug(fmt.Sprintf("use package log level=%q for package=%q", lvl, info.pkgName))
}
return true
}
return false
}
globalLvl := slog.Level(h.logLvl.Load())
if h.debug.Load() {
h.logger.Debug(fmt.Sprintf("use global log level=%q for package=%q", globalLvl, info.pkgName))
}
return lvl >= globalLvl
}
func (h *Handler) Handle(ctx context.Context, rec slog.Record) error {
return h.slogh.Handle(ctx, rec)
}
func (h *Handler) WithAttrs(attrs []slog.Attr) slog.Handler {
return h.slogh.WithAttrs(attrs)
}
func (h *Handler) WithGroup(name string) slog.Handler {
return h.slogh.WithGroup(name)
}
// GetConfig returns the current configuration, which may be adjusted and then used with UseConfig(cfg Config).
func (h *Handler) GetConfig() Config {
return *h.opts.Config
}
// UseConfig takes a new Config and immediately applies it to the current configuration.
// It also disables any active file watcher.
func (h *Handler) UseConfig(cfg Config) {
h.mu.Lock()
h.opts.EnableFileWatcher = false
h.opts.Config = &cfg
h.mu.Unlock()
h.initHandler()
h.logger.Debug(fmt.Sprintf("using config: %#v", *h.opts.Config))
}
// UseConfigTemporarily takes a new Config and immediately applies it to the current configuration.
// In contrast to UseConfig(cfg Config), this function automatically reverts to the state before calling the method,
// after revert amount of time has elapsed.
func (h *Handler) UseConfigTemporarily(cfg Config, revert time.Duration) {
h.mu.Lock()
oldCfg := h.GetConfig()
enableFileWatcher := h.opts.EnableFileWatcher
h.opts.EnableFileWatcher = false
h.opts.Config = &cfg
h.mu.Unlock()
h.initHandler()
go func() {
<-time.After(revert)
if enableFileWatcher {
h.UseConfigFile()
} else {
h.UseConfig(oldCfg)
}
h.logger.Debug(fmt.Sprintf("reverted config to original: %#v", oldCfg))
}()
h.logger.Debug(fmt.Sprintf("using config: %#v", *h.opts.Config))
}
// UseConfigFile takes a filename as an argument that will be used for watching a config file for changes.
// If no such filename is given, the Handler uses the already existing ConfigFile from the HandlerOptions or,
// if not present, falls back to the default config file (specified via defaultConfigFile).
func (h *Handler) UseConfigFile(cfgFile ...string) {
h.mu.Lock()
if len(cfgFile) == 1 && cfgFile[0] != "" {
h.opts.ConfigFile = cfgFile[0]
}
h.opts.EnableFileWatcher = true
h.mu.Unlock()
h.loadConfig().initHandler()
h.logger.Debug(fmt.Sprintf("using config file (%s): %#v", h.opts.ConfigFile, *h.opts.Config))
}
// GetLogLevel converts string log levels to slog.Level representation.
// Can be one of ["DEBUG", "INFO", "WARN" or "ERROR"].
// Additionally, it accepts the aforementioned strings +/- an integer for representing additional log levels, not
// defined by the log/slog package.
// Example: DEBUG-2 or ERROR+4
func (h *Handler) GetLogLevel(level string) slog.Level {
levelMap := map[string]slog.Level{
LogLevelDebug: slog.LevelDebug,
LogLevelInfo: slog.LevelInfo,
LogLevelWarn: slog.LevelWarn,
LogLevelError: slog.LevelError,
}
level = strings.ToUpper(level)
matches := logLevelRegex.FindStringSubmatch(level)
slogLevel := levelMap[defaultLogLevel]
if len(matches) != 5 {
//ss.logger.Debug(fmt.Sprintf("invalid log level: %q! -> fallback to log level %q", level, defaultLogLevel))
return slogLevel
}
slogLevel, ok := levelMap[matches[1]]
if !ok {
//ss.logger.Debug(fmt.Sprintf("invalid log level: %q! -> fallback to log level %q", level, defaultLogLevel))
return slogLevel
}
if matches[4] != "" {
nb, _ := strconv.Atoi(matches[4])
if matches[3] == "-" {
return slog.Level(int(slogLevel) - nb)
}
return slog.Level(int(slogLevel) + nb)
}
return slogLevel
}
type nilHandler struct{}
// NewNilHandler provides a nil slog.Handler for silencing slog.Log() calls.
func NewNilHandler() slog.Handler {
return &nilHandler{}
}
func (h *nilHandler) Enabled(_ context.Context, _ slog.Level) bool {
return false
}
func (h *nilHandler) Handle(_ context.Context, _ slog.Record) error {
return nil
}
func (h *nilHandler) WithAttrs([]slog.Attr) slog.Handler {
return h
}
func (h *nilHandler) WithGroup(_ string) slog.Handler {
return h
}
type internalHandler struct {
h slog.Handler
debug bool
}
func (ih *internalHandler) Enabled(_ context.Context, level slog.Level) bool {
if ih.debug {
return true
}
return level >= slog.LevelError
}
func (ih *internalHandler) Handle(ctx context.Context, record slog.Record) error {
return ih.h.Handle(ctx, record)
}
func (ih *internalHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
return &internalHandler{h: ih.h.WithAttrs(attrs), debug: ih.debug}
}
func (ih *internalHandler) WithGroup(name string) slog.Handler {
return &internalHandler{h: ih.h.WithGroup(name), debug: ih.debug}
}