Skip to content

Conversation

@lmittmann
Copy link
Owner

@lmittmann lmittmann commented May 19, 2025

This PR adds the function tint.Attr to easily write colored logs:

func Attr(color uint8, attr slog.Attr) slog.Attr

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

Example:

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
    },
}))

resolves #61

@lmittmann lmittmann changed the title add support for colored attributes via tint.Attr(color, attr) add colored attributes: tint.Attr(color, attr) May 19, 2025
@lmittmann lmittmann merged commit c6e7ac5 into main May 19, 2025
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Custom log level names with color

2 participants