Skip to content

Commit

Permalink
chore: Update logging example to use released version of log/slog
Browse files Browse the repository at this point in the history
chore: Fix logging example Panic() method to pretty print stack trace

Ref: #858
  • Loading branch information
ydarb committed Oct 19, 2023
1 parent 247397c commit 3425f06
Showing 1 changed file with 7 additions and 12 deletions.
19 changes: 7 additions & 12 deletions _examples/logging/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,23 +15,23 @@ import (
"os"
"time"

"golang.org/x/exp/slog"
"log/slog"

"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)

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 {
return slog.Attr{}
}
return a
},
}.NewJSONHandler(os.Stdout)
})

// Routes
r := chi.NewRouter()
Expand Down Expand Up @@ -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
}
Expand All @@ -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
Expand Down

0 comments on commit 3425f06

Please sign in to comment.