Source file
src/log/slog/example_test.go
1
2
3
4
5 package slog_test
6
7 import (
8 "context"
9 "log/slog"
10 "net/http"
11 "os"
12 "time"
13 )
14
15 func ExampleGroup() {
16 r, _ := http.NewRequest("GET", "localhost", nil)
17
18
19 logger := slog.New(
20 slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
21 ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
22 if a.Key == slog.TimeKey && len(groups) == 0 {
23 return slog.Attr{}
24 }
25 return a
26 },
27 }),
28 )
29 logger.Info("finished",
30 slog.Group("req",
31 slog.String("method", r.Method),
32 slog.String("url", r.URL.String())),
33 slog.Int("status", http.StatusOK),
34 slog.Duration("duration", time.Second))
35
36
37
38 }
39
40 func ExampleGroupAttrs() {
41 r, _ := http.NewRequest("POST", "localhost", http.NoBody)
42
43
44 logger := slog.New(
45 slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
46 Level: slog.LevelDebug,
47 ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
48 if a.Key == slog.TimeKey && len(groups) == 0 {
49 return slog.Attr{}
50 }
51 return a
52 },
53 }),
54 )
55
56
57 attrs := []slog.Attr{slog.String("method", r.Method)}
58 attrs = append(attrs, slog.String("url", r.URL.String()))
59
60 if r.Method == "POST" {
61 attrs = append(attrs, slog.Int("content-length", int(r.ContentLength)))
62 }
63
64
65 logger.LogAttrs(context.Background(), slog.LevelInfo,
66 "finished",
67 slog.Int("status", http.StatusOK),
68 slog.GroupAttrs("req", attrs...),
69 )
70
71
72 logger.LogAttrs(context.Background(), slog.LevelInfo,
73 "finished",
74 slog.Int("status", http.StatusOK),
75 slog.GroupAttrs("", attrs...),
76 )
77
78
79
80
81 }
82
View as plain text