-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathslogscope.go
More file actions
301 lines (264 loc) · 7.59 KB
/
Copy pathslogscope.go
File metadata and controls
301 lines (264 loc) · 7.59 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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
package slogscope
import (
"bytes"
"errors"
"fmt"
"log/slog"
"os"
"os/exec"
"runtime"
"strings"
"sync"
"sync/atomic"
"github.com/fsnotify/fsnotify"
"gopkg.in/yaml.v3"
)
// Constants for debug mode and defaults values.
const (
defaultLogLevel = LogLevelInfo
defaultConfigFile = "slogscope.yml"
)
// Available log levels for the Config.
const (
LogLevelDebug = "DEBUG"
LogLevelInfo = "INFO"
LogLevelWarn = "WARN"
LogLevelError = "ERROR"
)
// callSiteInfo represents the resolved log override settings for a call site.
type callSiteInfo struct {
pkgName string
overrideLvl slog.Level
hasOverride bool
}
// slogscope contains all required Handler configurations.
type slogscope struct {
h *Handler
slogh slog.Handler
opts *HandlerOptions
logLvl atomic.Int32 // Global log level (slog.Level)
debug atomic.Bool // Debug mode flag
pkgMapMu sync.RWMutex
pkgMap map[string]slog.Level // Map from package name to its log level
pcCacheMu sync.RWMutex
pcCache map[uintptr]callSiteInfo // Cache for PC to call site mapping
//lvlMap sync.Map
mu sync.Mutex
doneCh chan struct{}
logger *slog.Logger
}
// initConfigFileWatcher watches the specified config file for changes and reflects them instantly in their
// log response during program runtime without restarting.
func (ss *slogscope) initConfigFileWatcher() chan struct{} {
if !checkFileExists(ss.opts.ConfigFile) {
ss.logger.Debug(fmt.Sprintf("config file %q does not exists! -> file watcher is disabled.", ss.opts.ConfigFile))
return nil
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
ss.logger.Debug(err.Error())
return nil
}
// Add the config file to watch.
err = watcher.Add(ss.opts.ConfigFile)
if err != nil {
ss.logger.Debug(err.Error())
return nil
}
doneCh := make(chan struct{})
// Start listening for events.
go func() {
ss.logger.Debug(fmt.Sprintf("started file watcher for config file (%s).", ss.opts.ConfigFile))
closeWatcher := func() {
if err := watcher.Close(); err != nil {
ss.logger.Debug(fmt.Sprintf("file watcher error for config file (%s): %s.", ss.opts.ConfigFile, err.Error()))
return
}
ss.logger.Debug(fmt.Sprintf("stopped file watcher for config file (%s).", ss.opts.ConfigFile))
}
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
switch {
case event.Has(fsnotify.Remove):
ss.logger.Debug(fmt.Sprintf("config file (%s) was removed.", event.Name))
closeWatcher()
return
case event.Has(fsnotify.Rename):
ss.logger.Debug(fmt.Sprintf("config file (%s) was renamed.", event.Name))
closeWatcher()
return
case event.Has(fsnotify.Write):
ss.logger.Debug(fmt.Sprintf("config file (%s) was modified.", event.Name))
ss.loadConfig().initHandler()
closeWatcher()
return
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
ss.logger.Debug(fmt.Sprintf("file watcher error for config file (%s): %s.", ss.opts.ConfigFile, err.Error()))
case <-doneCh:
closeWatcher()
return
}
}
}()
return doneCh
}
// initHandler initializes the slogscope instance depending on the given HandlerOptions.
// If opts.EnableFileWatcher == true, the Handler will try to load the config from a config file,
// specified by HandlerOptions.ConfigFile (fallback filename is defaultConfigFile), and if that fails,
// it uses a default Config with "INFO" as global log level.
func (ss *slogscope) initHandler() {
ss.mu.Lock()
defer ss.mu.Unlock()
if ss.opts.Config == nil {
ss.opts.Config = &Config{
LogLevel: defaultLogLevel,
Packages: nil,
}
// Create a config file if it does not already exist.
if !checkFileExists(ss.opts.ConfigFile) {
ss.opts.Config.Packages = ss.createPackageList()
data, err := yaml.Marshal(ss.opts.Config)
if err != nil {
ss.logger.Error(err.Error())
}
err = os.WriteFile(ss.opts.ConfigFile, data, 0644)
if err != nil {
ss.logger.Error(err.Error())
}
}
}
ss.logger.Debug("use config:", "config", *ss.opts.Config)
// Set global log level and debug flag
ss.logLvl.Store(int32(ss.h.GetLogLevel(ss.opts.Config.LogLevel)))
ss.debug.Store(ss.opts.Debug)
ss.pkgMapMu.Lock()
ss.pkgMap = make(map[string]slog.Level)
for _, v := range ss.opts.Config.Packages {
name := v.Name
name = strings.TrimSuffix(name, "/...")
name = strings.TrimSuffix(name, "/*")
ss.pkgMap[name] = ss.h.GetLogLevel(v.LogLevel)
}
ss.pkgMapMu.Unlock()
// Clear the call-site cache on configuration updates to apply new overrides
ss.pcCacheMu.Lock()
ss.pcCache = make(map[uintptr]callSiteInfo)
ss.pcCacheMu.Unlock()
if ss.doneCh != nil {
close(ss.doneCh)
ss.doneCh = nil
}
if ss.opts.EnableFileWatcher && ss.opts.ConfigFile != "" {
ss.doneCh = ss.initConfigFileWatcher()
}
}
func (ss *slogscope) loadConfig() *slogscope {
ss.mu.Lock()
defer ss.mu.Unlock()
if !checkFileExists(ss.opts.ConfigFile) {
ss.logger.Debug(fmt.Sprintf("config file (%s) does not exists! -> file watcher is disabled.", ss.opts.ConfigFile))
ss.opts.Config = nil
return ss
}
data, err := os.ReadFile(ss.opts.ConfigFile)
if err != nil {
ss.logger.Debug(fmt.Sprintf("error reading config file (%s): %s", ss.opts.ConfigFile, err.Error()))
ss.opts.Config = nil
return ss
}
var cfg Config
err = yaml.Unmarshal(data, &cfg)
if err != nil {
ss.logger.Debug(fmt.Sprintf("error unmarshalling config file (%s): %s", ss.opts.ConfigFile, err.Error()))
ss.opts.Config = nil
return ss
}
ss.opts.Config = &cfg
ss.logger.Debug(fmt.Sprintf("config file (%s) loaded.", ss.opts.ConfigFile))
return ss
}
// resolveCallSite resolves the package name and finds the best hierarchical log level override
// for a given program counter, caching the result to keep subsequent checks near-instant.
func (ss *slogscope) resolveCallSite(pc uintptr) callSiteInfo {
ss.pcCacheMu.RLock()
if ss.pcCache != nil {
if info, ok := ss.pcCache[pc]; ok {
ss.pcCacheMu.RUnlock()
return info
}
}
ss.pcCacheMu.RUnlock()
// 1. Resolve package name
funcName := runtime.FuncForPC(pc).Name()
lastSlash := strings.LastIndexByte(funcName, '/')
if lastSlash < 0 {
lastSlash = 0
}
firstDot := strings.IndexByte(funcName[lastSlash:], '.') + lastSlash
pkgName := funcName[:firstDot]
// 2. Perform prefix walking to find nearest hierarchical override
ss.pkgMapMu.RLock()
curr := pkgName
var overrideLvl slog.Level
var hasOverride bool
for {
if lvl, ok := ss.pkgMap[curr]; ok {
overrideLvl = lvl
hasOverride = true
break
}
idx := strings.LastIndexByte(curr, '/')
if idx < 0 {
break
}
curr = curr[:idx]
}
ss.pkgMapMu.RUnlock()
info := callSiteInfo{
pkgName: pkgName,
overrideLvl: overrideLvl,
hasOverride: hasOverride,
}
ss.pcCacheMu.Lock()
if ss.pcCache == nil {
ss.pcCache = make(map[uintptr]callSiteInfo)
}
ss.pcCache[pc] = info
ss.pcCacheMu.Unlock()
return info
}
// checkFileExists returns true if a file exists at that location on disk.
func checkFileExists(filePath string) bool {
_, err := os.Stat(filePath)
return !errors.Is(err, os.ErrNotExist)
}
// createPackageList returns a list of the project package names retrieved via go list command
func (ss *slogscope) createPackageList() []Package {
var packages []Package
cmd := exec.Command("go", "list", "./...")
cmdOutput := &bytes.Buffer{}
cmd.Stdout = cmdOutput
err := cmd.Run()
if err != nil {
ss.logger.Error(err.Error())
return packages
}
pkgPaths := strings.Split(cmdOutput.String(), "\n")
for _, pkgPath := range pkgPaths {
if pkgPath != "" {
packages = append(packages, Package{
Name: pkgPath,
LogLevel: "ERROR",
})
}
}
return packages
}