Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

proposal: log/slog: add a method to convert a string to a Level #59416

Closed
siriusa51 opened this issue Apr 4, 2023 · 3 comments
Closed

proposal: log/slog: add a method to convert a string to a Level #59416

siriusa51 opened this issue Apr 4, 2023 · 3 comments

Comments

@siriusa51
Copy link

siriusa51 commented Apr 4, 2023

This is a proposal to add a method for converting a string to a Level. Here's an example:

func ParseLevel(level string) slog.Level {
	// convert string to Level ...
}

func main() {
	lvl := os.Getenv("LOG_LEVEL")
	level := ParseLevel(lvl)
	handler := slog.HandlerOptions{Level: level}.NewJSONHandler(os.Stdout)

	slog.SetDefault(slog.New(handler))
	slog.Info("hello world")
}

The benefit of providing this method is that, when using command-line or environment variables, I can specify the Level in string format without worrying about the specific numerical value of the Level. This kind of setting method is commonly found in various program startup parameters, such as:

./app -level=ERROR -output=./app.log

or

LOG_LEVEL=ERROR ./app (app just get level from os.Getenv("LOG_LEVEL") and set logger level)

I think the conversion effect of ParseLevel can be similar to:

// slog/level.go:60
func (l Level) String() string { // ... }

so the conversion effect as follows:

DEBUG -> Level(-4)
INFO -> Level(0)
WARN -> Level(4)
ERROR -> Level(8)
ERROR+2 -> LEVEL(10)
ERROR-2 -> LEVEL(6)
...
@gopherbot gopherbot added this to the Proposal milestone Apr 4, 2023
@ianlancetaylor
Copy link
Contributor

CC @jba

@siriusa51
Copy link
Author

siriusa51 commented Apr 4, 2023

I found that there is already an existing interface for this functionality, so I am closing the issue.

	debug := slog.Level(0)
	err := debug.UnmarshalText([]byte("debug-1"))
	if err != nil {
		return
	}
	println(debug)

@antichris
Copy link

@siriusa51, for future reference, var debug slog.Level is clearer. Currently it reads like debug := slog.LevelInfo, which feels weird.

(Sorry for the notification, everyone else.)

@golang golang locked and limited conversation to collaborators Apr 15, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants