diff --git a/_examples/logging/main.go b/_examples/logging/main.go index 304e3095..d674121d 100644 --- a/_examples/logging/main.go +++ b/_examples/logging/main.go @@ -15,7 +15,7 @@ import ( "os" "time" - "golang.org/x/exp/slog" + "log/slog" "github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5/middleware" @@ -23,7 +23,7 @@ import ( func main() { // Setup a JSON handler for the new log/slog library - slogJSONHandler := slog.HandlerOptions{ + slogJSONHandler := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{ // Remove default time slog.Attr, we create our own later ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { if a.Key == slog.TimeKey { @@ -31,7 +31,7 @@ func main() { } return a }, - }.NewJSONHandler(os.Stdout) + }) // Routes r := chi.NewRouter() @@ -92,7 +92,7 @@ func (l *StructuredLogger) NewLogEntry(r *http.Request) middleware.LogEntry { entry := StructuredLoggerEntry{Logger: slog.New(handler)} - entry.Logger.LogAttrs(slog.LevelInfo, "request started") + entry.Logger.Info("request started") return &entry } @@ -102,18 +102,13 @@ type StructuredLoggerEntry struct { } func (l *StructuredLoggerEntry) Write(status, bytes int, header http.Header, elapsed time.Duration, extra interface{}) { - l.Logger.LogAttrs(slog.LevelInfo, "request complete", - slog.Int("resp_status", status), + l.Logger.With(slog.Int("resp_status", status), slog.Int("resp_byte_length", bytes), - slog.Float64("resp_elapsed_ms", float64(elapsed.Nanoseconds())/1000000.0), - ) + slog.Float64("resp_elapsed_ms", float64(elapsed.Nanoseconds())/1000000.0)).Info("request complete") } func (l *StructuredLoggerEntry) Panic(v interface{}, stack []byte) { - l.Logger.LogAttrs(slog.LevelInfo, "", - slog.String("stack", string(stack)), - slog.String("panic", fmt.Sprintf("%+v", v)), - ) + middleware.PrintPrettyStack(v) } // Helper methods used by the application to get the request-scoped