slog.Info("This is info log") slog.Warn("This is warning log") slog.Error("This is error log")
日志输出: 2024/07/2315:26:01 INFO This is info log 2024/07/2315:26:01 WARN This is warning log 2024/07/2315:26:01 ERROR This is error log
输出参数的日志
name := "sss"
slog.Info("msg", slog.String("name", name)) slog.Error("ERROR: value is empty", slog.Any("name", name))
日志输出: 2024/07/2315:27:31 INFO msg name=sss 2024/07/2315:27:31 ERROR ERROR: value is empty name=sss
设置打印的日志
// 设置日志格式为JSON slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{}))) slog.Error("ERROR: value is empty", slog.Any("name", name)) // 设置日志为Text slog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{}))) slog.Error("ERROR: value is empty", slog.Any("name", name))
日志输出: {"time":"2024-07-23T15:27:31.890811+08:00","level":"ERROR","msg":"ERROR: value is empty","name":"sss"} time=2024-07-23T15:27:31.890+08:00 level=ERROR msg="ERROR: value is empty" name=sss
设置打印代码源
// 设置日志里面有代码行 slog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{AddSource: true}))) slog.Error("ERROR: value is empty", slog.Any("name", name))
日志输出: time=2024-07-23T15:27:31.890+08:00 level=ERROR source=/Users/joohwan/GolandProjects/go-tools/basic/slog/slog.go:24 msg="ERROR: value is empty" name=sss
设置日志写入文件
// 设置日志写入本地文件 f, err := os.Create("foo.log") if err != nil { panic(err) } defer f.Close() slog.SetDefault(slog.New(slog.NewJSONHandler(f, nil))) slog.Error("ERROR: value is empty", slog.Any("name", name))