/
handler.go
229 lines (190 loc) · 4.6 KB
/
handler.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
package logwise
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"os"
"runtime"
"slices"
"strings"
"sync"
"github.com/fatih/color"
"go.uber.org/zap/zapcore"
)
var (
_ slog.Handler = (*ConsoleHandler)(nil)
_ HandlerSyncer = (*handlerSyncer)(nil)
)
const timeLayout = "2006-01-02T15:04:05.000Z0700"
type HandlerOptions struct {
*slog.HandlerOptions
}
func (opts HandlerOptions) NewHandler(w io.Writer, encoding string) slog.Handler {
switch strings.ToLower(encoding) {
case "console":
return NewConsoleHandler(w, opts.HandlerOptions)
case "text":
return slog.NewTextHandler(w, opts.HandlerOptions)
default:
return slog.NewJSONHandler(w, opts.HandlerOptions)
}
}
type ConsoleHandler struct {
w io.Writer
opts slog.HandlerOptions
global []slog.Attr
groups []string
}
func NewConsoleHandler(w io.Writer, opts *slog.HandlerOptions, attrs ...slog.Attr) *ConsoleHandler {
return &ConsoleHandler{opts: *opts, w: w, global: attrs}
}
func (h *ConsoleHandler) clone() *ConsoleHandler {
return &ConsoleHandler{
global: slices.Clip(h.global),
groups: slices.Clip(h.groups),
opts: h.opts,
w: h.w,
}
}
func (h *ConsoleHandler) Enabled(_ context.Context, l slog.Level) bool {
minLevel := slog.LevelInfo
if h.opts.Level != nil {
minLevel = h.opts.Level.Level()
}
return l >= minLevel
}
func (h *ConsoleHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
c := h.clone()
c.global = append(c.global, attrs...)
return c
}
func (h *ConsoleHandler) WithGroup(name string) slog.Handler {
c := h.clone()
c.groups = append(c.groups, name)
return c
}
func (h *ConsoleHandler) Handle(_ context.Context, r slog.Record) error {
var buf bytes.Buffer
if !r.Time.IsZero() {
_, _ = buf.WriteString(spaces(r.Time.Format(timeLayout), 31))
}
_, _ = buf.WriteString(coloredLevel(r.Level))
if len(h.groups) > 0 {
_, _ = buf.WriteString(coloredGroup(strings.Join(h.groups, ".")))
}
if r.Message != "" {
_, _ = buf.WriteString(spaces(r.Message, 24))
}
attrs, sep := h.attrs(r)
attrs += h.addSource(r, sep)
if attrs != "" {
_, _ = buf.WriteString(fmt.Sprintf(" {%s}", attrs))
}
if err := buf.WriteByte('\n'); err != nil {
return err
}
_, err := h.w.Write(buf.Bytes())
return err
}
func (h *ConsoleHandler) attrs(r slog.Record) (string, string) {
var (
sep string
buf bytes.Buffer
fn func(a slog.Attr) bool
)
fn = func(a slog.Attr) bool {
v := a.Value.Resolve()
_, _ = buf.WriteString(fmt.Sprintf("%s\"%s\": ", sep, a.Key))
if v.Kind() == slog.KindGroup {
sep = ""
_ = buf.WriteByte('{')
for _, aa := range v.Group() {
_, _ = buf.WriteString(sep)
fn(aa)
}
_ = buf.WriteByte('}')
} else {
sep = ", "
if err, ok := v.Any().(error); ok {
_, _ = buf.WriteString(err.Error())
} else {
b, _ := json.Marshal(v.Any())
_, _ = buf.Write(b)
}
}
return true
}
for _, attr := range h.global {
fn(attr)
}
r.Attrs(fn)
return buf.String(), sep
}
func (h *ConsoleHandler) addSource(r slog.Record, sep string) string {
if h.opts.AddSource {
f := frame(r)
if f.File != "" {
return fmt.Sprintf("%s\"%s\": \"%s:%d\"", sep, slog.SourceKey, f.File, f.Line)
}
}
return ""
}
func frame(r slog.Record) runtime.Frame {
fs := runtime.CallersFrames([]uintptr{r.PC})
f, _ := fs.Next()
return f
}
func spaces(str string, min int) string {
if len(str) < min {
return str + strings.Repeat(" ", min-len(str)) + " "
}
return str + " "
}
func coloredLevel(level slog.Level) string {
str := spaces(level.String(), 7)
switch level {
case slog.LevelInfo:
return color.HiCyanString(str)
case slog.LevelWarn:
return color.HiYellowString(str)
case slog.LevelError:
return color.HiRedString(str)
default:
return color.HiWhiteString(str)
}
}
func coloredGroup(group string) string {
return color.HiGreenString(spaces(group, 16))
}
type HandlerSyncer interface {
Sync() error
}
type handlerSyncer struct {
slog.Handler
once sync.Once
syncer zapcore.WriteSyncer
}
func NewHandlerSyncer(syncer zapcore.WriteSyncer, handler slog.Handler) slog.Handler {
return &handlerSyncer{
Handler: handler,
syncer: syncer,
}
}
func (h *handlerSyncer) WithAttrs(attrs []slog.Attr) slog.Handler {
return NewHandlerSyncer(h.syncer, h.Handler.WithAttrs(attrs))
}
func (h *handlerSyncer) WithGroup(name string) slog.Handler {
return NewHandlerSyncer(h.syncer, h.Handler.WithGroup(name))
}
func (h *handlerSyncer) Sync() (err error) {
h.once.Do(func() {
if err1 := h.syncer.Sync(); err1 != nil &&
!(strings.Contains(err1.Error(), os.Stderr.Name()) || strings.Contains(err1.Error(), os.Stdout.Name())) {
err = err1
}
})
return
}