
官方文档展示了如何使用新的结构化日志记录包,但似乎省略了如何记录错误。
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()))
}
}有人提出了一个提案并关闭了它。我认为它最终会成为不必要的语法糖。
func ErrAttr(err error) slog.Attr {
return slog.Any("error", err)
}以上就是如何使用“log/slog”记录错误的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号