-
Notifications
You must be signed in to change notification settings - Fork 42
/
logger.go
235 lines (190 loc) · 5.83 KB
/
logger.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
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
package log
import (
"context"
"io"
"log/slog"
"os"
"sync"
"github.com/omni-network/omni/lib/errors"
charm "github.com/charmbracelet/log"
"github.com/muesli/termenv"
)
//nolint:gochecknoglobals // Global logger is our approach.
var (
global = newConsoleLogger()
globalMu = new(sync.RWMutex)
)
type loggerKey struct{}
// Init initializes the global logger with the given config.
// It also returns a copy of the context with the logger attached, see WithLogger.
// It returns an error if the config is invalid.
func Init(ctx context.Context, cfg Config) (context.Context, error) {
l, err := cfg.make()
if err != nil {
return nil, err
}
globalMu.Lock()
global = l
globalMu.Unlock()
zeroLogMetrics()
return WithLogger(ctx, l), nil
}
// WithLogger returns a copy of the context with which the logger
// is associated replacing the default global logger when logging with this context.
func WithLogger(ctx context.Context, logger *slog.Logger) context.Context {
return context.WithValue(ctx, loggerKey{}, logger)
}
// getLogger returns the logger from the context, or the global logger if not present.
func getLogger(ctx context.Context) *slog.Logger {
if l := ctx.Value(loggerKey{}); l != nil {
return l.(*slog.Logger) //nolint:forcetypeassert,revive // We know the type.
}
globalMu.RLock()
defer globalMu.RUnlock()
return global
}
func newLogfmtLogger(opts ...func(*options)) *slog.Logger {
o := defaultOptions()
for _, opt := range opts {
opt(&o)
}
handler := slog.NewTextHandler(o.Writer, &slog.HandlerOptions{
AddSource: true,
Level: o.Level,
ReplaceAttr: slogReplaceAtts(o),
})
return slog.New(handler)
}
func newJSONLogger(opts ...func(*options)) *slog.Logger {
o := defaultOptions()
for _, opt := range opts {
opt(&o)
}
handler := slog.NewJSONHandler(o.Writer, &slog.HandlerOptions{
AddSource: true,
Level: o.Level,
ReplaceAttr: slogReplaceAtts(o),
})
return slog.New(handler)
}
// newCLILogger returns a new cli logger which doesn't print timestamps, level, source or stacktraces.
func newCLILogger(opts ...func(*options)) *slog.Logger {
o := defaultOptions()
o.Level = slog.LevelInfo // Only show info and above
for _, opt := range opts {
opt(&o)
}
charmLevel, _ := charm.ParseLevel(o.Level.String()) // Ignore error as all slog levels are valid charm levels.
logger := charm.NewWithOptions(o.Writer, charm.Options{
ReportTimestamp: false,
Level: charmLevel,
})
styles := charm.DefaultStyles()
const padWidth = 90
styles.Message = styles.Message.Width(padWidth)
styles.Levels = nil
logger.SetStyles(styles)
logger.SetColorProfile(o.Color)
if o.Test {
return slog.New(stubHandler{Handler: logger, skip: true})
}
return slog.New(logger)
}
// newConsoleLogger returns a new console logger for the following opinionated style:
// - Colored log levels (if tty supports it)
// - Timestamps are concise with millisecond precision
// - Timestamps and structured keys are faint
// - Messages are right padded to 40 characters
// This is aimed at local-dev and debugging. Production should use json or logfmt.
func newConsoleLogger(opts ...func(*options)) *slog.Logger {
o := defaultOptions()
for _, opt := range opts {
opt(&o)
}
timeFormat := "06-01-02 15:04:05.000"
if o.Test {
timeFormat = "00-00-00 00:00:00"
}
charmLevel, _ := charm.ParseLevel(o.Level.String()) // Ignore error as all slog levels are valid charm levels.
logger := charm.NewWithOptions(o.Writer, charm.Options{
TimeFormat: timeFormat,
ReportTimestamp: true,
Level: charmLevel,
})
styles := charm.DefaultStyles()
styles.Timestamp = styles.Timestamp.Faint(true)
const padWidth = 40
styles.Message = styles.Message.Width(padWidth).Inline(true)
logger.SetStyles(styles)
logger.SetColorProfile(o.Color)
if o.Test {
return slog.New(stubHandler{Handler: logger})
}
return slog.New(logger)
}
// options configure new loggers.
type options struct {
Writer io.Writer // Write to some buffer
Level slog.Level
Color termenv.Profile
Test bool // Stubs non-deterministic output for tests.
}
func defaultOptions() options {
return options{
Writer: os.Stderr,
Level: slog.LevelDebug,
Color: termenv.ColorProfile(),
Test: false,
}
}
// WithNoopLogger returns a copy of the context with a noop logger which discards all logs.
func WithNoopLogger(ctx context.Context) context.Context {
return WithLogger(ctx, newConsoleLogger(func(o *options) {
o.Writer = io.Discard
}))
}
// WithCLILogger returns a copy of the context with a cli logger.
func WithCLILogger(ctx context.Context) context.Context {
return WithLogger(ctx, newCLILogger())
}
// stubHandler is a handler that replaces the stacktrace and source attributes with stubs.
type stubHandler struct {
slog.Handler
skip bool // Skip instead of stubbing.
}
func (t stubHandler) Handle(ctx context.Context, r slog.Record) error {
resp := slog.NewRecord(r.Time, r.Level, r.Message, r.PC)
r.Attrs(func(a slog.Attr) bool {
if a.Key == "stacktrace" {
if t.skip {
return true
}
resp.AddAttrs(slog.String("stacktrace", "<stacktrace>"))
} else {
resp.AddAttrs(a)
}
return true
})
if err := t.Handler.Handle(ctx, resp); err != nil {
return errors.Wrap(err, "handle")
}
return nil
}
// slogReplaceAtts returns a the slog replace attr function based on the test flag.
func slogReplaceAtts(o options) func(groups []string, a slog.Attr) slog.Attr {
if !o.Test {
return func(_ []string, a slog.Attr) slog.Attr { return a }
}
return func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey && len(groups) == 0 {
return slog.String(slog.TimeKey, "00-00-00 00:00:00")
}
if a.Key == slog.SourceKey && len(groups) == 0 {
return slog.String(slog.SourceKey, "<source>")
}
if a.Key == "stacktrace" && len(groups) == 0 {
return slog.String(slog.SourceKey, "<stacktrace>")
}
return a
}
}