-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathhandler.go
More file actions
179 lines (151 loc) · 4 KB
/
handler.go
File metadata and controls
179 lines (151 loc) · 4 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
package slogcolor
import (
"context"
"fmt"
"io"
"log/slog"
"maps"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"github.com/fatih/color"
)
func formatValue(v slog.Value, formatter func(slog.Value) string) string {
if formatter != nil {
return formatter(v)
}
return v.String()
}
// Handler is a colored slog handler.
type Handler struct {
groups []string
attrs []slog.Attr
opts Options
mu *sync.Mutex
out io.Writer
}
// NewHandler creates a new [Handler] with the specified options. If opts is nil, uses [DefaultOptions].
func NewHandler(out io.Writer, opts *Options) *Handler {
h := &Handler{out: out, mu: &sync.Mutex{}}
if opts == nil {
h.opts = *DefaultOptions
} else {
h.opts = *opts
}
tags := maps.Clone(DefaultLevelTags)
if opts.LevelTags != nil {
for k, v := range opts.LevelTags {
tags[k] = v
}
}
h.opts.LevelTags = tags
return h
}
func (h *Handler) clone() *Handler {
return &Handler{
groups: h.groups,
attrs: h.attrs,
opts: h.opts,
mu: h.mu,
out: h.out,
}
}
// Enabled implements slog.Handler.Enabled .
func (h *Handler) Enabled(_ context.Context, level slog.Level) bool {
return level >= h.opts.Level.Level()
}
// Handle implements slog.Handler.Handle .
func (h *Handler) Handle(_ context.Context, r slog.Record) error {
buf := getBuffer()
buf.Reset()
if !h.opts.NoTime && !r.Time.IsZero() {
buf.WriteString(color.New(color.Faint).Sprint(r.Time.Format(h.opts.TimeFormat)))
buf.WriteByte(' ')
}
buf.WriteString(h.opts.LevelTags[r.Level])
buf.WriteByte(' ')
if h.opts.SrcFileMode != Nop {
if r.PC != 0 {
f, _ := runtime.CallersFrames([]uintptr{r.PC}).Next()
var filename string
switch h.opts.SrcFileMode {
case Nop:
break
case ShortFile:
filename = filepath.Base(f.File)
case LongFile:
filename = f.File
}
lineStr := fmt.Sprintf(":%d", f.Line)
formatted := fmt.Sprintf("%s ", filename+lineStr)
if h.opts.SrcFileLength > 0 {
maxFilenameLen := h.opts.SrcFileLength - len(lineStr) - 1
if len(filename) > maxFilenameLen {
filename = filename[:maxFilenameLen] // Truncate if too long
}
lenStr := strconv.Itoa(h.opts.SrcFileLength)
formatted = fmt.Sprintf("%-"+lenStr+"s", filename+lineStr)
}
buf.WriteString(formatted)
}
}
// we need the attributes here, as we can print a longer string if there are no attributes
var attrs []slog.Attr
attrs = append(attrs, h.attrs...)
r.Attrs(func(a slog.Attr) bool {
attrs = append(attrs, a)
return true
})
buf.WriteString(h.opts.MsgPrefix)
formattedMessage := r.Message
if h.opts.MsgLength > 0 && len(attrs) > 0 {
if len(formattedMessage) > h.opts.MsgLength {
formattedMessage = formattedMessage[:h.opts.MsgLength-1] + "…" // Truncate and add ellipsis if too long
} else {
// Pad with spaces if too short
lenStr := strconv.Itoa(h.opts.MsgLength)
formattedMessage = fmt.Sprintf("%-"+lenStr+"s", formattedMessage)
}
}
if h.opts.MsgColor == nil {
h.opts.MsgColor = color.New() // set to empty otherwise we have a null pointer
}
buf.WriteString(h.opts.MsgColor.Sprint(formattedMessage))
for _, a := range attrs {
buf.WriteByte(' ')
for i, g := range h.groups {
buf.WriteString(color.New(color.FgCyan).Sprint(g))
if i != len(h.groups) {
buf.WriteString(color.New(color.FgCyan).Sprint("."))
}
}
keyColor := color.New(color.FgCyan)
if strings.Contains(a.Key, "err") {
keyColor = color.New(color.FgRed)
}
buf.WriteString(keyColor.Sprintf("%s=", a.Key) + formatValue(a.Value, h.opts.ValueFormatter))
}
buf.WriteByte('\n')
if h.opts.NoColor {
stripANSI(buf)
}
h.mu.Lock()
_, err := io.Copy(h.out, buf)
h.mu.Unlock()
freeBuffer(buf)
return err
}
// WithGroup implements slog.Handler.WithGroup .
func (h *Handler) WithGroup(name string) slog.Handler {
h2 := h.clone()
h2.groups = append(h2.groups, name)
return h2
}
// WithAttrs implements slog.Handler.WithAttrs .
func (h *Handler) WithAttrs(attrs []slog.Attr) slog.Handler {
h2 := h.clone()
h2.attrs = append(h2.attrs, attrs...)
return h2
}