The official documentation shows how to use the new structured logging package, but seems to omit how to log errors.
https://pkg.go.dev/log/slog
package main import ( "fmt" "log/slog" "os" ) func demoFunction() error { return fmt.Errorf("oh no: %v", 123) } func main() { logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)) slog.SetDefault(logger) slog.Info("info demo", "count", 3) slog.Warn("warn demo", slog.String("somekey", "somevalue")) slog.Error("error demo", slog.Int("someintkey", 123)) err := demoFunction() if err != nil { // Here I'm logging the error as a string, but I presume there is a better way // possibly that will log stack trace info as well. slog.Error("the demo function got an error.", slog.String("error", err.Error())) } }
Someone made a proposal and closed it. I think it ends up being unnecessary syntactic sugar.
It seems that some people have decided to wrap slog.Any calls
func ErrAttr(err error) slog.Attr { return slog.Any("error", err) }
The above is the detailed content of How to log errors using 'log/slog'. For more information, please follow other related articles on the PHP Chinese website!