pax_global_header00006660000000000000000000000064150210045370014507gustar00rootroot0000000000000052 comment=401cb97c7812b9e0d98109e0b0f69a57a26116ec golang-github-lmittmann-tint-1.1.2/000077500000000000000000000000001502100453700172145ustar00rootroot00000000000000golang-github-lmittmann-tint-1.1.2/.github/000077500000000000000000000000001502100453700205545ustar00rootroot00000000000000golang-github-lmittmann-tint-1.1.2/.github/workflows/000077500000000000000000000000001502100453700226115ustar00rootroot00000000000000golang-github-lmittmann-tint-1.1.2/.github/workflows/go.yml000066400000000000000000000012671502100453700237470ustar00rootroot00000000000000name: Go on: push: branches: - main pull_request: jobs: lint: name: Lint runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 with: go-version: "1.24" - name: fmt run: diff -u <(echo -n) <(gofmt -s -d .) - name: vet run: go vet ./... - name: staticcheck run: go run honnef.co/go/tools/cmd/staticcheck@latest ./... test: name: Test runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 with: go-version: "1.21" - name: test run: TZ="" go test ./... -race -tags=faketime golang-github-lmittmann-tint-1.1.2/LICENSE000066400000000000000000000020521502100453700202200ustar00rootroot00000000000000MIT License Copyright (c) 2023 lmittmann Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. golang-github-lmittmann-tint-1.1.2/README.md000066400000000000000000000072511502100453700205000ustar00rootroot00000000000000# `tint`: 🌈 **slog.Handler** that writes tinted logs [![Go Reference](https://pkg.go.dev/badge/github.com/lmittmann/tint.svg)](https://pkg.go.dev/github.com/lmittmann/tint#section-documentation) [![Go Report Card](https://goreportcard.com/badge/github.com/lmittmann/tint)](https://goreportcard.com/report/github.com/lmittmann/tint)

Package `tint` implements a zero-dependency [`slog.Handler`](https://pkg.go.dev/log/slog#Handler) that writes tinted (colorized) logs. Its output format is inspired by the `zerolog.ConsoleWriter` and [`slog.TextHandler`](https://pkg.go.dev/log/slog#TextHandler). The output format can be customized using [`Options`](https://pkg.go.dev/github.com/lmittmann/tint#Options) which is a drop-in replacement for [`slog.HandlerOptions`](https://pkg.go.dev/log/slog#HandlerOptions). ``` go get github.com/lmittmann/tint ``` ## Usage ```go w := os.Stderr // Create a new logger logger := slog.New(tint.NewHandler(w, nil)) // Set global logger with custom options slog.SetDefault(slog.New( tint.NewHandler(w, &tint.Options{ Level: slog.LevelDebug, TimeFormat: time.Kitchen, }), )) ``` ### Customize Attributes `ReplaceAttr` can be used to alter or drop attributes. If set, it is called on each non-group attribute before it is logged. See [`slog.HandlerOptions`](https://pkg.go.dev/log/slog#HandlerOptions) for details. ```go // Create a new logger with a custom TRACE level: const LevelTrace = slog.LevelDebug - 4 w := os.Stderr logger := slog.New(tint.NewHandler(w, &tint.Options{ Level: LevelTrace, ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { if a.Key == slog.LevelKey && len(groups) == 0 { level, ok := a.Value.Any().(slog.Level) if ok && level <= LevelTrace { return tint.Attr(13, slog.String(a.Key, "TRC")) } } return a }, })) ``` ```go // Create a new logger that doesn't write the time w := os.Stderr logger := slog.New( tint.NewHandler(w, &tint.Options{ ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { if a.Key == slog.TimeKey && len(groups) == 0 { return slog.Attr{} } return a }, }), ) ``` ```go // Create a new logger that writes all errors in red w := os.Stderr logger := slog.New( tint.NewHandler(w, &tint.Options{ ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { if a.Value.Kind() == slog.KindAny { if _, ok := a.Value.Any().(error); ok { return tint.Attr(9, a) } } return a }, }), ) ``` ### Automatically Enable Colors Colors are enabled by default. Use the `Options.NoColor` field to disable color output. To automatically enable colors based on terminal capabilities, use e.g., the [`go-isatty`](https://github.com/mattn/go-isatty) package: ```go w := os.Stderr logger := slog.New( tint.NewHandler(w, &tint.Options{ NoColor: !isatty.IsTerminal(w.Fd()), }), ) ``` ### Windows Support Color support on Windows can be added by using e.g., the [`go-colorable`](https://github.com/mattn/go-colorable) package: ```go w := os.Stderr logger := slog.New( tint.NewHandler(colorable.NewColorable(w), nil), ) ``` golang-github-lmittmann-tint-1.1.2/buffer.go000066400000000000000000000013051502100453700210130ustar00rootroot00000000000000package tint import "sync" type buffer []byte var bufPool = sync.Pool{ New: func() any { b := make(buffer, 0, 1024) return (*buffer)(&b) }, } func newBuffer() *buffer { return bufPool.Get().(*buffer) } func (b *buffer) Free() { // To reduce peak allocation, return only smaller buffers to the pool. const maxBufferSize = 16 << 10 if cap(*b) <= maxBufferSize { *b = (*b)[:0] bufPool.Put(b) } } func (b *buffer) Write(bytes []byte) (int, error) { *b = append(*b, bytes...) return len(bytes), nil } func (b *buffer) WriteByte(char byte) error { *b = append(*b, char) return nil } func (b *buffer) WriteString(str string) (int, error) { *b = append(*b, str...) return len(str), nil } golang-github-lmittmann-tint-1.1.2/go.mod000066400000000000000000000000521502100453700203170ustar00rootroot00000000000000module github.com/lmittmann/tint go 1.21 golang-github-lmittmann-tint-1.1.2/handler.go000066400000000000000000000431601502100453700211640ustar00rootroot00000000000000/* Package tint implements a zero-dependency [slog.Handler] that writes tinted (colorized) logs. The output format is inspired by the [zerolog.ConsoleWriter] and [slog.TextHandler]. The output format can be customized using [Options], which is a drop-in replacement for [slog.HandlerOptions]. # Customize Attributes Options.ReplaceAttr can be used to alter or drop attributes. If set, it is called on each non-group attribute before it is logged. See [slog.HandlerOptions] for details. Create a new logger with a custom TRACE level: const LevelTrace = slog.LevelDebug - 4 w := os.Stderr logger := slog.New(tint.NewHandler(w, &tint.Options{ Level: LevelTrace, ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { if a.Key == slog.LevelKey && len(groups) == 0 { level, ok := a.Value.Any().(slog.Level) if ok && level <= LevelTrace { return tint.Attr(13, slog.String(a.Key, "TRC")) } } return a }, })) Create a new logger that doesn't write the time: w := os.Stderr logger := slog.New( tint.NewHandler(w, &tint.Options{ ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { if a.Key == slog.TimeKey && len(groups) == 0 { return slog.Attr{} } return a }, }), ) Create a new logger that writes all errors in red: w := os.Stderr logger := slog.New( tint.NewHandler(w, &tint.Options{ ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { if a.Value.Kind() == slog.KindAny { if _, ok := a.Value.Any().(error); ok { return tint.Attr(9, a) } } return a }, }), ) # Automatically Enable Colors Colors are enabled by default. Use the Options.NoColor field to disable color output. To automatically enable colors based on terminal capabilities, use e.g., the [go-isatty] package: w := os.Stderr logger := slog.New( tint.NewHandler(w, &tint.Options{ NoColor: !isatty.IsTerminal(w.Fd()), }), ) # Windows Support Color support on Windows can be added by using e.g., the [go-colorable] package: w := os.Stderr logger := slog.New( tint.NewHandler(colorable.NewColorable(w), nil), ) [zerolog.ConsoleWriter]: https://pkg.go.dev/github.com/rs/zerolog#ConsoleWriter [go-isatty]: https://pkg.go.dev/github.com/mattn/go-isatty [go-colorable]: https://pkg.go.dev/github.com/mattn/go-colorable */ package tint import ( "context" "encoding" "fmt" "io" "log/slog" "path/filepath" "reflect" "runtime" "strconv" "strings" "sync" "time" "unicode" "unicode/utf8" ) const ( // ANSI modes ansiEsc = '\u001b' ansiReset = "\u001b[0m" ansiFaint = "\u001b[2m" ansiResetFaint = "\u001b[22m" ansiBrightRed = "\u001b[91m" ansiBrightGreen = "\u001b[92m" ansiBrightYellow = "\u001b[93m" errKey = "err" defaultLevel = slog.LevelInfo defaultTimeFormat = time.StampMilli ) // Options for a slog.Handler that writes tinted logs. A zero Options consists // entirely of default values. // // Options can be used as a drop-in replacement for [slog.HandlerOptions]. type Options struct { // Enable source code location (Default: false) AddSource bool // Minimum level to log (Default: slog.LevelInfo) Level slog.Leveler // ReplaceAttr is called to rewrite each non-group attribute before it is logged. // See https://pkg.go.dev/log/slog#HandlerOptions for details. ReplaceAttr func(groups []string, attr slog.Attr) slog.Attr // Time format (Default: time.StampMilli) TimeFormat string // Disable color (Default: false) NoColor bool } func (o *Options) setDefaults() { if o.Level == nil { o.Level = defaultLevel } if o.TimeFormat == "" { o.TimeFormat = defaultTimeFormat } } // NewHandler creates a [slog.Handler] that writes tinted logs to Writer w, // using the default options. If opts is nil, the default options are used. func NewHandler(w io.Writer, opts *Options) slog.Handler { if opts == nil { opts = &Options{} } opts.setDefaults() return &handler{ mu: &sync.Mutex{}, w: w, opts: *opts, } } // handler implements a [slog.Handler]. type handler struct { attrsPrefix string groupPrefix string groups []string mu *sync.Mutex w io.Writer opts Options } func (h *handler) clone() *handler { return &handler{ attrsPrefix: h.attrsPrefix, groupPrefix: h.groupPrefix, groups: h.groups, mu: h.mu, // mutex shared among all clones of this handler w: h.w, opts: h.opts, } } func (h *handler) Enabled(_ context.Context, level slog.Level) bool { return level >= h.opts.Level.Level() } func (h *handler) Handle(_ context.Context, r slog.Record) error { // get a buffer from the sync pool buf := newBuffer() defer buf.Free() rep := h.opts.ReplaceAttr // write time if !r.Time.IsZero() { val := r.Time.Round(0) // strip monotonic to match Attr behavior if rep == nil { h.appendTintTime(buf, r.Time, -1) buf.WriteByte(' ') } else if a := rep(nil /* groups */, slog.Time(slog.TimeKey, val)); a.Key != "" { val, color := h.resolve(a.Value) if val.Kind() == slog.KindTime { h.appendTintTime(buf, val.Time(), color) } else { h.appendTintValue(buf, val, false, color, true) } buf.WriteByte(' ') } } // write level if rep == nil { h.appendTintLevel(buf, r.Level, -1) buf.WriteByte(' ') } else if a := rep(nil /* groups */, slog.Any(slog.LevelKey, r.Level)); a.Key != "" { val, color := h.resolve(a.Value) if val.Kind() == slog.KindAny { if lvlVal, ok := val.Any().(slog.Level); ok { h.appendTintLevel(buf, lvlVal, color) } else { h.appendTintValue(buf, val, false, color, false) } } else { h.appendTintValue(buf, val, false, color, false) } buf.WriteByte(' ') } // write source if h.opts.AddSource { fs := runtime.CallersFrames([]uintptr{r.PC}) f, _ := fs.Next() if f.File != "" { src := &slog.Source{ Function: f.Function, File: f.File, Line: f.Line, } if rep == nil { if h.opts.NoColor { appendSource(buf, src) } else { buf.WriteString(ansiFaint) appendSource(buf, src) buf.WriteString(ansiReset) } buf.WriteByte(' ') } else if a := rep(nil /* groups */, slog.Any(slog.SourceKey, src)); a.Key != "" { val, color := h.resolve(a.Value) h.appendTintValue(buf, val, false, color, true) buf.WriteByte(' ') } } } // write message if rep == nil { buf.WriteString(r.Message) buf.WriteByte(' ') } else if a := rep(nil /* groups */, slog.String(slog.MessageKey, r.Message)); a.Key != "" { val, color := h.resolve(a.Value) h.appendTintValue(buf, val, false, color, false) buf.WriteByte(' ') } // write handler attributes if len(h.attrsPrefix) > 0 { buf.WriteString(h.attrsPrefix) } // write attributes r.Attrs(func(attr slog.Attr) bool { h.appendAttr(buf, attr, h.groupPrefix, h.groups) return true }) if len(*buf) == 0 { buf.WriteByte('\n') } else { (*buf)[len(*buf)-1] = '\n' // replace last space with newline } h.mu.Lock() defer h.mu.Unlock() _, err := h.w.Write(*buf) return err } func (h *handler) WithAttrs(attrs []slog.Attr) slog.Handler { if len(attrs) == 0 { return h } h2 := h.clone() buf := newBuffer() defer buf.Free() // write attributes to buffer for _, attr := range attrs { h.appendAttr(buf, attr, h.groupPrefix, h.groups) } h2.attrsPrefix = h.attrsPrefix + string(*buf) return h2 } func (h *handler) WithGroup(name string) slog.Handler { if name == "" { return h } h2 := h.clone() h2.groupPrefix += name + "." h2.groups = append(h2.groups, name) return h2 } func (h *handler) appendTintTime(buf *buffer, t time.Time, color int16) { if h.opts.NoColor { *buf = t.AppendFormat(*buf, h.opts.TimeFormat) } else { if color >= 0 { appendAnsi(buf, uint8(color), true) } else { buf.WriteString(ansiFaint) } *buf = t.AppendFormat(*buf, h.opts.TimeFormat) buf.WriteString(ansiReset) } } func (h *handler) appendTintLevel(buf *buffer, level slog.Level, color int16) { str := func(base string, val slog.Level) []byte { if val == 0 { return []byte(base) } else if val > 0 { return strconv.AppendInt(append([]byte(base), '+'), int64(val), 10) } return strconv.AppendInt([]byte(base), int64(val), 10) } if !h.opts.NoColor { if color >= 0 { appendAnsi(buf, uint8(color), false) } else { switch { case level < slog.LevelInfo: case level < slog.LevelWarn: buf.WriteString(ansiBrightGreen) case level < slog.LevelError: buf.WriteString(ansiBrightYellow) default: buf.WriteString(ansiBrightRed) } } } switch { case level < slog.LevelInfo: buf.Write(str("DBG", level-slog.LevelDebug)) case level < slog.LevelWarn: buf.Write(str("INF", level-slog.LevelInfo)) case level < slog.LevelError: buf.Write(str("WRN", level-slog.LevelWarn)) default: buf.Write(str("ERR", level-slog.LevelError)) } if !h.opts.NoColor && level >= slog.LevelInfo { buf.WriteString(ansiReset) } } func appendSource(buf *buffer, src *slog.Source) { dir, file := filepath.Split(src.File) buf.WriteString(filepath.Join(filepath.Base(dir), file)) buf.WriteByte(':') *buf = strconv.AppendInt(*buf, int64(src.Line), 10) } func (h *handler) resolve(val slog.Value) (resolvedVal slog.Value, color int16) { if !h.opts.NoColor && val.Kind() == slog.KindLogValuer { if tintVal, ok := val.Any().(tintValue); ok { return tintVal.Value.Resolve(), int16(tintVal.Color) } } return val.Resolve(), -1 } func (h *handler) appendAttr(buf *buffer, attr slog.Attr, groupsPrefix string, groups []string) { var color int16 // -1 if no color attr.Value, color = h.resolve(attr.Value) if rep := h.opts.ReplaceAttr; rep != nil && attr.Value.Kind() != slog.KindGroup { attr = rep(groups, attr) var colorRep int16 attr.Value, colorRep = h.resolve(attr.Value) if colorRep >= 0 { color = colorRep } } if attr.Equal(slog.Attr{}) { return } if attr.Value.Kind() == slog.KindGroup { if attr.Key != "" { groupsPrefix += attr.Key + "." groups = append(groups, attr.Key) } for _, groupAttr := range attr.Value.Group() { h.appendAttr(buf, groupAttr, groupsPrefix, groups) } return } if h.opts.NoColor { h.appendKey(buf, attr.Key, groupsPrefix) h.appendValue(buf, attr.Value, true) } else { if color >= 0 { appendAnsi(buf, uint8(color), true) h.appendKey(buf, attr.Key, groupsPrefix) buf.WriteString(ansiResetFaint) h.appendValue(buf, attr.Value, true) buf.WriteString(ansiReset) } else { buf.WriteString(ansiFaint) h.appendKey(buf, attr.Key, groupsPrefix) buf.WriteString(ansiReset) h.appendValue(buf, attr.Value, true) } } buf.WriteByte(' ') } func (h *handler) appendKey(buf *buffer, key, groups string) { appendString(buf, groups+key, true, !h.opts.NoColor) buf.WriteByte('=') } func (h *handler) appendValue(buf *buffer, v slog.Value, quote bool) { switch v.Kind() { case slog.KindString: appendString(buf, v.String(), quote, !h.opts.NoColor) case slog.KindInt64: *buf = strconv.AppendInt(*buf, v.Int64(), 10) case slog.KindUint64: *buf = strconv.AppendUint(*buf, v.Uint64(), 10) case slog.KindFloat64: *buf = strconv.AppendFloat(*buf, v.Float64(), 'g', -1, 64) case slog.KindBool: *buf = strconv.AppendBool(*buf, v.Bool()) case slog.KindDuration: appendString(buf, v.Duration().String(), quote, !h.opts.NoColor) case slog.KindTime: *buf = appendRFC3339Millis(*buf, v.Time()) case slog.KindAny: defer func() { // Copied from log/slog/handler.go. if r := recover(); r != nil { // If it panics with a nil pointer, the most likely cases are // an encoding.TextMarshaler or error fails to guard against nil, // in which case "" seems to be the feasible choice. // // Adapted from the code in fmt/print.go. if v := reflect.ValueOf(v.Any()); v.Kind() == reflect.Pointer && v.IsNil() { buf.WriteString("") return } // Otherwise just print the original panic message. appendString(buf, fmt.Sprintf("!PANIC: %v", r), true, !h.opts.NoColor) } }() switch cv := v.Any().(type) { case encoding.TextMarshaler: data, err := cv.MarshalText() if err != nil { break } appendString(buf, string(data), quote, !h.opts.NoColor) case *slog.Source: appendSource(buf, cv) default: appendString(buf, fmt.Sprintf("%+v", cv), quote, !h.opts.NoColor) } } } func (h *handler) appendTintValue(buf *buffer, val slog.Value, quote bool, color int16, faint bool) { if h.opts.NoColor { h.appendValue(buf, val, quote) } else { if color >= 0 { appendAnsi(buf, uint8(color), faint) } else if faint { buf.WriteString(ansiFaint) } h.appendValue(buf, val, quote) if color >= 0 || faint { buf.WriteString(ansiReset) } } } // Copied from log/slog/handler.go. func appendRFC3339Millis(b []byte, t time.Time) []byte { // Format according to time.RFC3339Nano since it is highly optimized, // but truncate it to use millisecond resolution. // Unfortunately, that format trims trailing 0s, so add 1/10 millisecond // to guarantee that there are exactly 4 digits after the period. const prefixLen = len("2006-01-02T15:04:05.000") n := len(b) t = t.Truncate(time.Millisecond).Add(time.Millisecond / 10) b = t.AppendFormat(b, time.RFC3339Nano) b = append(b[:n+prefixLen], b[n+prefixLen+1:]...) // drop the 4th digit return b } func appendAnsi(buf *buffer, color uint8, faint bool) { buf.WriteString("\u001b[") if faint { buf.WriteString("2;") } if color < 8 { *buf = strconv.AppendUint(*buf, uint64(color)+30, 10) } else if color < 16 { *buf = strconv.AppendUint(*buf, uint64(color)+82, 10) } else { buf.WriteString("38;5;") *buf = strconv.AppendUint(*buf, uint64(color), 10) } buf.WriteByte('m') } func appendString(buf *buffer, s string, quote, color bool) { if quote && !color { // trim ANSI escape sequences var inEscape bool s = cut(s, func(r rune) bool { if r == ansiEsc { inEscape = true } else if inEscape && unicode.IsLetter(r) { inEscape = false return true } return inEscape }) } quote = quote && needsQuoting(s) switch { case color && quote: s = strconv.Quote(s) s = strings.ReplaceAll(s, `\x1b`, string(ansiEsc)) buf.WriteString(s) case !color && quote: *buf = strconv.AppendQuote(*buf, s) default: buf.WriteString(s) } } func cut(s string, f func(r rune) bool) string { var res []rune for i := 0; i < len(s); { r, size := utf8.DecodeRuneInString(s[i:]) if r == utf8.RuneError { break } if !f(r) { res = append(res, r) } i += size } return string(res) } // Copied from log/slog/text_handler.go. func needsQuoting(s string) bool { if len(s) == 0 { return true } for i := 0; i < len(s); { b := s[i] if b < utf8.RuneSelf { // Quote anything except a backslash that would need quoting in a // JSON string, as well as space and '=' if b != '\\' && (b == ' ' || b == '=' || !safeSet[b]) { return true } i++ continue } r, size := utf8.DecodeRuneInString(s[i:]) if r == utf8.RuneError || unicode.IsSpace(r) || !unicode.IsPrint(r) { return true } i += size } return false } // Copied from log/slog/json_handler.go. // // safeSet is extended by the ANSI escape code "\u001b". var safeSet = [utf8.RuneSelf]bool{ ' ': true, '!': true, '"': false, '#': true, '$': true, '%': true, '&': true, '\'': true, '(': true, ')': true, '*': true, '+': true, ',': true, '-': true, '.': true, '/': true, '0': true, '1': true, '2': true, '3': true, '4': true, '5': true, '6': true, '7': true, '8': true, '9': true, ':': true, ';': true, '<': true, '=': true, '>': true, '?': true, '@': true, 'A': true, 'B': true, 'C': true, 'D': true, 'E': true, 'F': true, 'G': true, 'H': true, 'I': true, 'J': true, 'K': true, 'L': true, 'M': true, 'N': true, 'O': true, 'P': true, 'Q': true, 'R': true, 'S': true, 'T': true, 'U': true, 'V': true, 'W': true, 'X': true, 'Y': true, 'Z': true, '[': true, '\\': false, ']': true, '^': true, '_': true, '`': true, 'a': true, 'b': true, 'c': true, 'd': true, 'e': true, 'f': true, 'g': true, 'h': true, 'i': true, 'j': true, 'k': true, 'l': true, 'm': true, 'n': true, 'o': true, 'p': true, 'q': true, 'r': true, 's': true, 't': true, 'u': true, 'v': true, 'w': true, 'x': true, 'y': true, 'z': true, '{': true, '|': true, '}': true, '~': true, '\u007f': true, '\u001b': true, } type tintValue struct { slog.Value Color uint8 } // LogValue implements the [slog.LogValuer] interface. func (v tintValue) LogValue() slog.Value { return v.Value } // Err returns a tinted (colorized) [slog.Attr] that will be written in red color // by the [tint.Handler]. When used with any other [slog.Handler], it behaves as // // slog.Any("err", err) func Err(err error) slog.Attr { return Attr(9, slog.Any(errKey, err)) } // Attr returns a tinted (colorized) [slog.Attr] that will be written in the // specified color by the [tint.Handler]. When used with any other [slog.Handler], it behaves as a // plain [slog.Attr]. // // Use the uint8 color value to specify the color of the attribute: // // - 0-7: standard ANSI colors // - 8-15: high intensity ANSI colors // - 16-231: 216 colors (6×6×6 cube) // - 232-255: grayscale from dark to light in 24 steps // // See https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit func Attr(color uint8, attr slog.Attr) slog.Attr { attr.Value = slog.AnyValue(tintValue{attr.Value, color}) return attr } golang-github-lmittmann-tint-1.1.2/handler_test.go000066400000000000000000000623101502100453700222210ustar00rootroot00000000000000package tint_test import ( "bytes" "context" "errors" "io" "log/slog" "os" "slices" "strconv" "strings" "sync" "testing" "time" "github.com/lmittmann/tint" ) func Example() { w := os.Stderr logger := slog.New(tint.NewHandler(w, &tint.Options{ Level: slog.LevelDebug, TimeFormat: time.Kitchen, })) logger.Info("Starting server", "addr", ":8080", "env", "production") logger.Debug("Connected to DB", "db", "myapp", "host", "localhost:5432") logger.Warn("Slow request", "method", "GET", "path", "/users", "duration", 497*time.Millisecond) logger.Error("DB connection lost", tint.Err(errors.New("connection reset")), "db", "myapp") // Output: } // Create a new logger that writes all errors in red: func Example_redErrors() { w := os.Stderr logger := slog.New(tint.NewHandler(w, &tint.Options{ ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { if a.Value.Kind() == slog.KindAny { if _, ok := a.Value.Any().(error); ok { return tint.Attr(9, a) } } return a }, })) logger.Error("DB connection lost", "error", errors.New("connection reset"), "db", "myapp") // Output: } // Create a new logger with a custom TRACE level: func Example_traceLevel() { const LevelTrace = slog.LevelDebug - 4 w := os.Stderr logger := slog.New(tint.NewHandler(w, &tint.Options{ Level: LevelTrace, ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { if a.Key == slog.LevelKey && len(groups) == 0 { level, ok := a.Value.Any().(slog.Level) if ok && level <= LevelTrace { return tint.Attr(13, slog.String(a.Key, "TRC")) } } return a }, })) logger.Log(context.Background(), LevelTrace, "DB query", "query", "SELECT * FROM users", "duration", 543*time.Microsecond) // Output: } var ( faketime = time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC) handlerTests = []struct { Opts *tint.Options F func(l *slog.Logger) Want string }{ { F: func(l *slog.Logger) { l.Info("test", "key", "val") }, Want: `Nov 10 23:00:00.000 INF test key=val`, }, { F: func(l *slog.Logger) { l.Error("test", tint.Err(errors.New("fail"))) }, Want: `Nov 10 23:00:00.000 ERR test err=fail`, }, { F: func(l *slog.Logger) { l.Info("test", slog.Group("group", slog.String("key", "val"), tint.Err(errors.New("fail")))) }, Want: `Nov 10 23:00:00.000 INF test group.key=val group.err=fail`, }, { F: func(l *slog.Logger) { l.WithGroup("group").Info("test", "key", "val") }, Want: `Nov 10 23:00:00.000 INF test group.key=val`, }, { F: func(l *slog.Logger) { l.With("key", "val").Info("test", "key2", "val2") }, Want: `Nov 10 23:00:00.000 INF test key=val key2=val2`, }, { F: func(l *slog.Logger) { l.Info("test", "k e y", "v a l") }, Want: `Nov 10 23:00:00.000 INF test "k e y"="v a l"`, }, { F: func(l *slog.Logger) { l.WithGroup("g r o u p").Info("test", "key", "val") }, Want: `Nov 10 23:00:00.000 INF test "g r o u p.key"=val`, }, { F: func(l *slog.Logger) { l.Info("test", "slice", []string{"a", "b", "c"}, "map", map[string]int{"a": 1, "b": 2, "c": 3}) }, Want: `Nov 10 23:00:00.000 INF test slice="[a b c]" map="map[a:1 b:2 c:3]"`, }, { Opts: &tint.Options{ AddSource: true, NoColor: true, }, F: func(l *slog.Logger) { l.Info("test", "key", "val") }, Want: `Nov 10 23:00:00.000 INF tint/handler_test.go:133 test key=val`, }, { Opts: &tint.Options{ TimeFormat: time.Kitchen, NoColor: true, }, F: func(l *slog.Logger) { l.Info("test", "key", "val") }, Want: `11:00PM INF test key=val`, }, { Opts: &tint.Options{ ReplaceAttr: drop(slog.TimeKey), NoColor: true, }, F: func(l *slog.Logger) { l.Info("test", "key", "val") }, Want: `INF test key=val`, }, { Opts: &tint.Options{ ReplaceAttr: drop(slog.LevelKey), NoColor: true, }, F: func(l *slog.Logger) { l.Info("test", "key", "val") }, Want: `Nov 10 23:00:00.000 test key=val`, }, { Opts: &tint.Options{ ReplaceAttr: drop(slog.MessageKey), NoColor: true, }, F: func(l *slog.Logger) { l.Info("test", "key", "val") }, Want: `Nov 10 23:00:00.000 INF key=val`, }, { Opts: &tint.Options{ ReplaceAttr: drop(slog.TimeKey, slog.LevelKey, slog.MessageKey), NoColor: true, }, F: func(l *slog.Logger) { l.Info("test", "key", "val") }, Want: `key=val`, }, { Opts: &tint.Options{ ReplaceAttr: drop("key"), NoColor: true, }, F: func(l *slog.Logger) { l.Info("test", "key", "val") }, Want: `Nov 10 23:00:00.000 INF test`, }, { Opts: &tint.Options{ ReplaceAttr: drop("key"), NoColor: true, }, F: func(l *slog.Logger) { l.WithGroup("group").Info("test", "key", "val", "key2", "val2") }, Want: `Nov 10 23:00:00.000 INF test group.key=val group.key2=val2`, }, { Opts: &tint.Options{ ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { if a.Key == "key" && len(groups) == 1 && groups[0] == "group" { return slog.Attr{} } return a }, NoColor: true, }, F: func(l *slog.Logger) { l.WithGroup("group").Info("test", "key", "val", "key2", "val2") }, Want: `Nov 10 23:00:00.000 INF test group.key2=val2`, }, { Opts: &tint.Options{ ReplaceAttr: replace(slog.IntValue(42), slog.TimeKey), NoColor: true, }, F: func(l *slog.Logger) { l.Info("test", "key", "val") }, Want: `42 INF test key=val`, }, { Opts: &tint.Options{ ReplaceAttr: replace(slog.StringValue("INFO"), slog.LevelKey), NoColor: true, }, F: func(l *slog.Logger) { l.Info("test", "key", "val") }, Want: `Nov 10 23:00:00.000 INFO test key=val`, }, { Opts: &tint.Options{ ReplaceAttr: replace(slog.IntValue(42), slog.MessageKey), NoColor: true, }, F: func(l *slog.Logger) { l.Info("test", "key", "val") }, Want: `Nov 10 23:00:00.000 INF 42 key=val`, }, { Opts: &tint.Options{ ReplaceAttr: replace(slog.IntValue(42), "key"), NoColor: true, }, F: func(l *slog.Logger) { l.With("key", "val").Info("test", "key2", "val2") }, Want: `Nov 10 23:00:00.000 INF test key=42 key2=val2`, }, { Opts: &tint.Options{ ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { return slog.Attr{} }, NoColor: true, }, F: func(l *slog.Logger) { l.Info("test", "key", "val") }, Want: ``, }, { F: func(l *slog.Logger) { l.Info("test", "key", "") }, Want: `Nov 10 23:00:00.000 INF test key=""`, }, { F: func(l *slog.Logger) { l.Info("test", "", "val") }, Want: `Nov 10 23:00:00.000 INF test ""=val`, }, { F: func(l *slog.Logger) { l.Info("test", "", "") }, Want: `Nov 10 23:00:00.000 INF test ""=""`, }, { Opts: &tint.Options{ TimeFormat: time.DateOnly, ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { if len(groups) == 0 && a.Key == slog.TimeKey { return slog.Time(slog.TimeKey, a.Value.Time().Add(24*time.Hour)) } return a }, NoColor: true, }, F: func(l *slog.Logger) { l.Info("test") }, Want: `2009-11-11 INF test`, }, { F: func(l *slog.Logger) { l.Info("test", "lvl", slog.LevelWarn) }, Want: `Nov 10 23:00:00.000 INF test lvl=WARN`, }, { Opts: &tint.Options{NoColor: false}, F: func(l *slog.Logger) { l.Info("test", "lvl", slog.LevelWarn) }, Want: "\033[2mNov 10 23:00:00.000\033[0m \033[92mINF\033[0m test \033[2mlvl=\033[0mWARN", }, { Opts: &tint.Options{ ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { return tint.Attr(13, a) }, }, F: func(l *slog.Logger) { l.Info("test") }, Want: "\033[2;95mNov 10 23:00:00.000\033[0m \033[95mINF\033[0m \033[95mtest\033[0m", }, { Opts: &tint.Options{NoColor: false}, F: func(l *slog.Logger) { l.Error("test", tint.Err(errors.New("fail"))) }, Want: "\033[2mNov 10 23:00:00.000\033[0m \033[91mERR\033[0m test \033[2;91merr=\033[22mfail\033[0m", }, { Opts: &tint.Options{NoColor: false}, F: func(l *slog.Logger) { l.Info("test", tint.Attr(10, slog.String("key", "value"))) }, Want: "\033[2mNov 10 23:00:00.000\033[0m \033[92mINF\033[0m test \033[2;92mkey=\033[22mvalue\033[0m", }, { Opts: &tint.Options{NoColor: false}, F: func(l *slog.Logger) { l.Info("test", tint.Attr(226, slog.String("key", "value"))) }, Want: "\033[2mNov 10 23:00:00.000\033[0m \033[92mINF\033[0m test \033[2;38;5;226mkey=\033[22mvalue\033[0m", }, { Opts: &tint.Options{ NoColor: false, ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { if a.Key == slog.MessageKey && len(groups) == 0 { return tint.Attr(10, a) } return a }, }, F: func(l *slog.Logger) { l.Info("test", "key", "value") }, Want: "\033[2mNov 10 23:00:00.000\033[0m \033[92mINF\033[0m \033[92mtest\033[0m \033[2mkey=\033[0mvalue", }, { Opts: &tint.Options{ NoColor: false, ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { if a.Key == slog.TimeKey && len(groups) == 0 { return tint.Attr(10, a) } return a }, }, F: func(l *slog.Logger) { l.Info("test", "key", "value") }, Want: "\033[2;92mNov 10 23:00:00.000\033[0m \033[92mINF\033[0m test \033[2mkey=\033[0mvalue", }, { Opts: &tint.Options{ NoColor: false, ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { if a.Key == slog.TimeKey && len(groups) == 0 { return tint.Attr(10, slog.String(a.Key, a.Value.Time().Format(time.StampMilli))) } return a }, }, F: func(l *slog.Logger) { l.Info("test", "key", "value") }, Want: "\033[2;92mNov 10 23:00:00.000\033[0m \033[92mINF\033[0m test \033[2mkey=\033[0mvalue", }, { Opts: &tint.Options{ AddSource: true, NoColor: false, ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { if a.Key == slog.SourceKey && len(groups) == 0 { return tint.Attr(10, a) } return a }, }, F: func(l *slog.Logger) { l.Info("test") }, Want: "\033[2mNov 10 23:00:00.000\033[0m \033[92mINF\033[0m \033[2;92mtint/handler_test.go:410\033[0m test", }, { Opts: &tint.Options{ NoColor: false, Level: slog.LevelDebug - 4, ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { if a.Key == slog.LevelKey && len(groups) == 0 { level, ok := a.Value.Any().(slog.Level) if ok && level <= slog.LevelDebug-4 { return slog.String(a.Key, "TRC") } } return a }, }, F: func(l *slog.Logger) { const levelTrace = slog.LevelDebug - 4 l.Log(context.TODO(), levelTrace, "test") }, Want: "\033[2mNov 10 23:00:00.000\033[0m TRC test", }, { Opts: &tint.Options{ NoColor: false, Level: slog.LevelDebug - 4, ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { if a.Key == slog.LevelKey && len(groups) == 0 { level, ok := a.Value.Any().(slog.Level) if ok && level <= slog.LevelDebug-4 { return tint.Attr(13, slog.String(a.Key, "TRC")) } } return a }, }, F: func(l *slog.Logger) { const levelTrace = slog.LevelDebug - 4 l.Log(context.TODO(), levelTrace, "test") }, Want: "\033[2mNov 10 23:00:00.000\033[0m \033[95mTRC\033[0m test", }, { // https://github.com/lmittmann/tint/issues/8 F: func(l *slog.Logger) { l.Log(context.TODO(), slog.LevelInfo+1, "test") }, Want: `Nov 10 23:00:00.000 INF+1 test`, }, { Opts: &tint.Options{ Level: slog.LevelDebug - 1, NoColor: true, }, F: func(l *slog.Logger) { l.Log(context.TODO(), slog.LevelDebug-1, "test") }, Want: `Nov 10 23:00:00.000 DBG-1 test`, }, { // https://github.com/lmittmann/tint/issues/12 F: func(l *slog.Logger) { l.Error("test", slog.Any("error", errors.New("fail"))) }, Want: `Nov 10 23:00:00.000 ERR test error=fail`, }, { // https://github.com/lmittmann/tint/issues/15 F: func(l *slog.Logger) { l.Error("test", tint.Err(nil)) }, Want: `Nov 10 23:00:00.000 ERR test err=`, }, { // https://github.com/lmittmann/tint/pull/26 Opts: &tint.Options{ ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { if a.Key == slog.TimeKey && len(groups) == 0 { return slog.Time(slog.TimeKey, a.Value.Time().Add(24*time.Hour)) } return a }, NoColor: true, }, F: func(l *slog.Logger) { l.Error("test") }, Want: `Nov 11 23:00:00.000 ERR test`, }, { // https://github.com/lmittmann/tint/pull/27 F: func(l *slog.Logger) { l.Info("test", "a", "b", slog.Group("", slog.String("c", "d")), "e", "f") }, Want: `Nov 10 23:00:00.000 INF test a=b c=d e=f`, }, { // https://github.com/lmittmann/tint/pull/30 // drop built-in attributes in a grouped log Opts: &tint.Options{ ReplaceAttr: drop(slog.TimeKey, slog.LevelKey, slog.MessageKey, slog.SourceKey), AddSource: true, NoColor: true, }, F: func(l *slog.Logger) { l.WithGroup("group").Info("test", "key", "val") }, Want: `group.key=val`, }, { // https://github.com/lmittmann/tint/issues/36 Opts: &tint.Options{ ReplaceAttr: func(g []string, a slog.Attr) slog.Attr { if len(g) == 0 && a.Key == slog.LevelKey { _ = a.Value.Any().(slog.Level) } return a }, NoColor: true, }, F: func(l *slog.Logger) { l.Info("test") }, Want: `Nov 10 23:00:00.000 INF test`, }, { // https://github.com/lmittmann/tint/issues/37 Opts: &tint.Options{ AddSource: true, ReplaceAttr: func(g []string, a slog.Attr) slog.Attr { return a }, NoColor: true, }, F: func(l *slog.Logger) { l.Info("test") }, Want: `Nov 10 23:00:00.000 INF tint/handler_test.go:540 test`, }, { // https://github.com/lmittmann/tint/issues/44 F: func(l *slog.Logger) { l = l.WithGroup("group") l.Error("test", tint.Err(errTest)) }, Want: `Nov 10 23:00:00.000 ERR test group.err=fail`, }, { // https://github.com/lmittmann/tint/issues/55 F: func(l *slog.Logger) { l.Info("test", "key", struct { A int B *string }{A: 123}) }, Want: `Nov 10 23:00:00.000 INF test key="{A:123 B:}"`, }, { // https://github.com/lmittmann/tint/issues/59 Opts: &tint.Options{NoColor: false}, F: func(l *slog.Logger) { l.Info("test", "color", "\033[92mgreen\033[0m") }, Want: "\033[2mNov 10 23:00:00.000\033[0m \033[92mINF\033[0m test \033[2mcolor=\033[0m\033[92mgreen\033[0m", }, { Opts: &tint.Options{NoColor: false}, F: func(l *slog.Logger) { l.Info("test", "color", "\033[92mgreen quoted\033[0m") }, Want: "\033[2mNov 10 23:00:00.000\033[0m \033[92mINF\033[0m test \033[2mcolor=\033[0m\"\033[92mgreen quoted\033[0m\"", }, { Opts: &tint.Options{NoColor: true}, F: func(l *slog.Logger) { l.Info("test", "color", "\033[92mgreen\033[0m") }, Want: `Nov 10 23:00:00.000 INF test color=green`, }, { Opts: &tint.Options{NoColor: true}, F: func(l *slog.Logger) { l.Info("test", "color", "\033[92mgreen quoted\033[0m") }, Want: `Nov 10 23:00:00.000 INF test color="green quoted"`, }, { // https://github.com/lmittmann/tint/pull/66 F: func(l *slog.Logger) { errAttr := tint.Err(errors.New("fail")) errAttr.Key = "error" l.Error("test", errAttr) }, Want: `Nov 10 23:00:00.000 ERR test error=fail`, }, { // https://github.com/lmittmann/tint/issues/85 F: func(l *slog.Logger) { var t *time.Time l.Info("test", "time", t) }, Want: `Nov 10 23:00:00.000 INF test time=`, }, { // https://github.com/lmittmann/tint/pull/94 F: func(l *slog.Logger) { l.Info("test", "time", testTime) }, Want: `Nov 10 23:00:00.000 INF test time=2022-05-01T00:00:00.000Z`, }, { // https://github.com/lmittmann/tint/pull/96 Opts: &tint.Options{ NoColor: false, ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { return a }, }, F: func(l *slog.Logger) { l.Info("test", tint.Attr(10, slog.String("key", "val"))) }, Want: "\033[2mNov 10 23:00:00.000\033[0m \033[92mINF\033[0m test \033[2;92mkey=\033[22mval\033[0m", }, { Opts: &tint.Options{ NoColor: false, ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { return tint.Attr(13, a) }, }, F: func(l *slog.Logger) { l.Info("test", tint.Attr(10, slog.String("key", "val"))) }, Want: "\033[2;95mNov 10 23:00:00.000\033[0m \033[95mINF\033[0m \033[95mtest\033[0m \033[2;95mkey=\033[22mval\033[0m", }, } ) func TestHandler(t *testing.T) { if now := time.Now(); !faketime.Equal(now) || now.Location().String() != "UTC" { t.Skip(`run: TZ="" go test -tags=faketime`) } for i, test := range handlerTests { t.Run(strconv.Itoa(i), func(t *testing.T) { var buf bytes.Buffer if test.Opts == nil { test.Opts = &tint.Options{NoColor: true} } l := slog.New(tint.NewHandler(&buf, test.Opts)) test.F(l) got, foundNewline := strings.CutSuffix(buf.String(), "\n") if !foundNewline { t.Fatalf("missing newline") } if test.Want != got { t.Fatalf("(-want +got)\n- %s\n+ %s", test.Want, got) } }) } } // drop returns a ReplaceAttr that drops the given keys. func drop(keys ...string) func([]string, slog.Attr) slog.Attr { return func(groups []string, a slog.Attr) slog.Attr { if len(groups) > 0 { return a } for _, key := range keys { if a.Key == key { a = slog.Attr{} } } return a } } func replace(new slog.Value, keys ...string) func([]string, slog.Attr) slog.Attr { return func(groups []string, a slog.Attr) slog.Attr { if len(groups) > 0 { return a } for _, key := range keys { if a.Key == key { a.Value = new } } return a } } func TestReplaceAttr(t *testing.T) { if now := time.Now(); !faketime.Equal(now) || now.Location().String() != "UTC" { t.Skip(`run: TZ="" go test -tags=faketime`) } tests := [][]any{ {}, {"key", "val"}, {"key", "val", slog.Group("group", "key2", "val2")}, {"key", "val", slog.Group("group", "key2", "val2", slog.Group("group2", "key3", "val3"))}, } type replaceAttrParams struct { Groups []string Attr slog.Attr } replaceAttrRecorder := func(record *[]replaceAttrParams) func([]string, slog.Attr) slog.Attr { return func(groups []string, a slog.Attr) slog.Attr { *record = append(*record, replaceAttrParams{groups, a}) return a } } for i, test := range tests { t.Run(strconv.Itoa(i), func(t *testing.T) { slogRecord := make([]replaceAttrParams, 0) slogLogger := slog.New(slog.NewTextHandler(io.Discard, &slog.HandlerOptions{ ReplaceAttr: replaceAttrRecorder(&slogRecord), })) slogLogger.Log(context.TODO(), slog.LevelInfo, "", test...) tintRecord := make([]replaceAttrParams, 0) tintLogger := slog.New(tint.NewHandler(io.Discard, &tint.Options{ ReplaceAttr: replaceAttrRecorder(&tintRecord), })) tintLogger.Log(context.TODO(), slog.LevelInfo, "", test...) if !slices.EqualFunc(slogRecord, tintRecord, func(a, b replaceAttrParams) bool { return slices.Equal(a.Groups, b.Groups) && a.Attr.Equal(b.Attr) }) { t.Fatalf("(-want +got)\n- %v\n+ %v", slogRecord, tintRecord) } }) } } func TestAttr(t *testing.T) { if now := time.Now(); !faketime.Equal(now) || now.Location().String() != "UTC" { t.Skip(`run: TZ="" go test -tags=faketime`) } t.Run("text", func(t *testing.T) { var buf bytes.Buffer logger := slog.New(slog.NewTextHandler(&buf, nil)) logger.Info("test", tint.Attr(10, slog.String("key", "val"))) want := `time=2009-11-10T23:00:00.000Z level=INFO msg=test key=val` if got := strings.TrimSpace(buf.String()); want != got { t.Fatalf("(-want +got)\n- %s\n+ %s", want, got) } }) t.Run("json", func(t *testing.T) { var buf bytes.Buffer logger := slog.New(slog.NewJSONHandler(&buf, nil)) logger.Info("test", tint.Attr(10, slog.String("key", "val"))) want := `{"time":"2009-11-10T23:00:00Z","level":"INFO","msg":"test","key":"val"}` if got := strings.TrimSpace(buf.String()); want != got { t.Fatalf("(-want +got)\n- %s\n+ %s", want, got) } }) } // TestClonedHandlersSynchronizeWriter tests that cloned handlers synchronize writer // writes with each other such that a logger can be shared among multiple goroutines. func TestClonedHandlersSynchronizeWriter(t *testing.T) { // logSomething calls `With(...)` and uses the resulting logger to create and use a cloned handler. logSomething := func(wg *sync.WaitGroup, logger *slog.Logger, loggerID int) { defer wg.Done() logger = logger.With("withLoggerID", loggerID) logger.Info("test") } logger := slog.New(tint.NewHandler(&bytes.Buffer{}, &tint.Options{})) // start and wait for two goroutines var wg sync.WaitGroup wg.Add(2) go logSomething(&wg, logger, 1) go logSomething(&wg, logger, 2) wg.Wait() } // See https://github.com/golang/exp/blob/master/slog/benchmarks/benchmarks_test.go#L25 // // Run e.g.: // // go test -bench=. -count=10 | benchstat -col /h /dev/stdin func BenchmarkLogAttrs(b *testing.B) { handler := []struct { Name string H slog.Handler }{ {"tint", tint.NewHandler(io.Discard, nil)}, {"text", slog.NewTextHandler(io.Discard, nil)}, {"json", slog.NewJSONHandler(io.Discard, nil)}, {"discard", new(discarder)}, } benchmarks := []struct { Name string F func(*slog.Logger) }{ { "5 args", func(logger *slog.Logger) { logger.LogAttrs(context.TODO(), slog.LevelInfo, testMessage, slog.String("string", testString), slog.Int("status", testInt), slog.Duration("duration", testDuration), slog.Time("time", testTime), slog.Any("error", errTest), ) }, }, { "5 args custom level", func(logger *slog.Logger) { logger.LogAttrs(context.TODO(), slog.LevelInfo+1, testMessage, slog.String("string", testString), slog.Int("status", testInt), slog.Duration("duration", testDuration), slog.Time("time", testTime), slog.Any("error", errTest), ) }, }, { "10 args", func(logger *slog.Logger) { logger.LogAttrs(context.TODO(), slog.LevelInfo, testMessage, slog.String("string", testString), slog.Int("status", testInt), slog.Duration("duration", testDuration), slog.Time("time", testTime), slog.Any("error", errTest), slog.String("string", testString), slog.Int("status", testInt), slog.Duration("duration", testDuration), slog.Time("time", testTime), slog.Any("error", errTest), ) }, }, { "40 args", func(logger *slog.Logger) { logger.LogAttrs(context.TODO(), slog.LevelInfo, testMessage, slog.String("string", testString), slog.Int("status", testInt), slog.Duration("duration", testDuration), slog.Time("time", testTime), slog.Any("error", errTest), slog.String("string", testString), slog.Int("status", testInt), slog.Duration("duration", testDuration), slog.Time("time", testTime), slog.Any("error", errTest), slog.String("string", testString), slog.Int("status", testInt), slog.Duration("duration", testDuration), slog.Time("time", testTime), slog.Any("error", errTest), slog.String("string", testString), slog.Int("status", testInt), slog.Duration("duration", testDuration), slog.Time("time", testTime), slog.Any("error", errTest), slog.String("string", testString), slog.Int("status", testInt), slog.Duration("duration", testDuration), slog.Time("time", testTime), slog.Any("error", errTest), slog.String("string", testString), slog.Int("status", testInt), slog.Duration("duration", testDuration), slog.Time("time", testTime), slog.Any("error", errTest), slog.String("string", testString), slog.Int("status", testInt), slog.Duration("duration", testDuration), slog.Time("time", testTime), slog.Any("error", errTest), slog.String("string", testString), slog.Int("status", testInt), slog.Duration("duration", testDuration), slog.Time("time", testTime), slog.Any("error", errTest), ) }, }, { "error", func(logger *slog.Logger) { logger.LogAttrs(context.TODO(), slog.LevelError, testMessage, tint.Err(errTest), ) }, }, { "attr", func(logger *slog.Logger) { logger.LogAttrs(context.TODO(), slog.LevelError, testMessage, tint.Attr(9, slog.String("string", testString)), ) }, }, } for _, h := range handler { b.Run("h="+h.Name, func(b *testing.B) { for _, bench := range benchmarks { b.Run(bench.Name, func(b *testing.B) { b.ReportAllocs() logger := slog.New(h.H) for i := 0; i < b.N; i++ { bench.F(logger) } }) } }) } } // discarder is a slog.Handler that discards all records. type discarder struct{} func (*discarder) Enabled(context.Context, slog.Level) bool { return true } func (*discarder) Handle(context.Context, slog.Record) error { return nil } func (d *discarder) WithAttrs(attrs []slog.Attr) slog.Handler { return d } func (d *discarder) WithGroup(name string) slog.Handler { return d } var ( testMessage = "Test logging, but use a somewhat realistic message length." testTime = time.Date(2022, time.May, 1, 0, 0, 0, 0, time.UTC) testString = "7e3b3b2aaeff56a7108fe11e154200dd/7819479873059528190" testInt = 32768 testDuration = 23 * time.Second errTest = errors.New("fail") )