lmittmann / tint

🌈 slog.Handler that writes tinted (colorized) logs
https://pkg.go.dev/github.com/lmittmann/tint
MIT License
723 stars 38 forks source link

Custom log level names with color #61

Open nasdf opened 4 months ago

nasdf commented 4 months ago

It'd be great to be able to customize the log level names and keep the colors.

I think simple package level variables would work for most use cases.

var (
  InfoLevelName  = "INF"
  ErrorLevelName = "ERR"
)

Happy to submit a PR if you agree with the feature.

lmittmann commented 4 months ago

This is a popular request. You can currently customize levels via the ReplaceAttr option. But I agree that it is not very handy, since you need to manage colors on your own. I am not sure how the API could look like yet, but modifying global variables is not the way.

iamsumit commented 4 months ago

Raised a PR to provide this feature.

mpiorowski commented 1 month ago

if anyone will need this, thats how i manage to do it:

const (
    ansiReset          = "\033[0m"
    ansiFaint          = "\033[2m"
    ansiResetFaint     = "\033[22m"
    ansiBrightRed      = "\033[91m"
    ansiBrightGreen    = "\033[92m"
    ansiBrightYellow   = "\033[93m"
    ansiBrightRedFaint = "\033[91;2m"
)

// InitLogger initializes the logger
func InitLogger() {
    var log slog.Level
    if LOG_LEVEL == "info" {
        log = slog.LevelInfo
    } else {
        log = slog.LevelDebug
    }
    slog.SetDefault(slog.New(
        tint.NewHandler(os.Stderr, &tint.Options{
            AddSource:  true,
            Level:      log,
            TimeFormat: time.Kitchen,
            ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
                if a.Key == slog.LevelKey {
                    level := a.Value.Any().(slog.Level)
                    switch {
                    case level == slog.LevelError:
                        a.Value = slog.StringValue(ansiBrightRed + "ERROR" + ansiReset)
                    case level == slog.LevelWarn:
                        a.Value = slog.StringValue(ansiBrightYellow + "WARN" + ansiReset)
                    case level == slog.LevelInfo:
                        a.Value = slog.StringValue(ansiBrightGreen + "INFO" + ansiReset)
                    case level == slog.LevelDebug:
                        a.Value = slog.StringValue(ansiBrightRedFaint + "DEBUG" + ansiReset)
                    default:
                        a.Value = slog.StringValue("UNKNOWN")
                    }
                }
                return a
            },
        }),
    ))
}