tint icon indicating copy to clipboard operation
tint copied to clipboard

Custom log level names with color

Open nasdf opened this issue 1 year ago • 3 comments

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.

nasdf avatar Apr 22 '24 21:04 nasdf

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.

lmittmann avatar Apr 23 '24 06:04 lmittmann

Raised a PR to provide this feature.

iamsumit avatar May 15 '24 09:05 iamsumit

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

mpiorowski avatar Jul 24 '24 20:07 mpiorowski