Source file
src/cdr.dev/slog/example_test.go
1 package slog_test
2
3 import (
4 "context"
5 "io"
6 "net"
7 "os"
8 "testing"
9 "time"
10
11 "go.opencensus.io/trace"
12 "golang.org/x/xerrors"
13
14 "cdr.dev/slog"
15 "cdr.dev/slog/sloggers/sloghuman"
16 "cdr.dev/slog/sloggers/slogstackdriver"
17 "cdr.dev/slog/sloggers/slogtest"
18 )
19
20 func Example() {
21 log := slog.Make(sloghuman.Sink(os.Stdout))
22
23 log.Info(context.Background(), "my message here",
24 slog.F("field_name", "something or the other"),
25 slog.F("some_map", slog.M(
26 slog.F("nested_fields", time.Date(2000, time.February, 5, 4, 4, 4, 0, time.UTC)),
27 )),
28 slog.Error(
29 xerrors.Errorf("wrap1: %w",
30 xerrors.Errorf("wrap2: %w",
31 io.EOF,
32 ),
33 ),
34 ),
35 )
36
37
38
39
40
41
42
43
44
45 }
46
47 func Example_struct() {
48 l := slog.Make(sloghuman.Sink(os.Stdout))
49
50 type hello struct {
51 Meow int `json:"meow"`
52 Bar string `json:"bar"`
53 M time.Time `json:"m"`
54 }
55
56 l.Info(context.Background(), "check out my structure",
57 slog.F("hello", hello{
58 Meow: 1,
59 Bar: "barbar",
60 M: time.Date(2000, time.February, 5, 4, 4, 4, 0, time.UTC),
61 }),
62 )
63
64
65 }
66
67 func Example_testing() {
68
69 var t testing.TB
70
71 slogtest.Info(t, "my message here",
72 slog.F("field_name", "something or the other"),
73 )
74
75
76 }
77
78 func Example_tracing() {
79 log := slog.Make(sloghuman.Sink(os.Stdout))
80
81 ctx, _ := trace.StartSpan(context.Background(), "spanName")
82
83 log.Info(ctx, "my msg", slog.F("hello", "hi"))
84
85
86 }
87
88 func Example_multiple() {
89 l := slog.Make(sloghuman.Sink(os.Stdout))
90
91 f, err := os.OpenFile("stackdriver", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
92 if err != nil {
93 l.Fatal(context.Background(), "failed to open stackdriver log file", slog.Error(err))
94 }
95
96 l = l.AppendSinks(slogstackdriver.Sink(f))
97
98 l.Info(context.Background(), "log to stdout and stackdriver")
99
100
101 }
102
103 func ExampleWith() {
104 ctx := slog.With(context.Background(), slog.F("field", 1))
105
106 l := slog.Make(sloghuman.Sink(os.Stdout))
107 l.Info(ctx, "msg")
108
109
110 }
111
112 func ExampleStdlib() {
113 ctx := slog.With(context.Background(), slog.F("field", 1))
114 l := slog.Stdlib(ctx, slog.Make(sloghuman.Sink(os.Stdout)), slog.LevelInfo)
115
116 l.Print("msg")
117
118
119 }
120
121 func ExampleLogger_Named() {
122 ctx := context.Background()
123
124 l := slog.Make(sloghuman.Sink(os.Stdout))
125 l = l.Named("http")
126 l.Info(ctx, "received request", slog.F("remote address", net.IPv4(127, 0, 0, 1)))
127
128
129 }
130
131 func ExampleLogger_Leveled() {
132 ctx := context.Background()
133
134 l := slog.Make(sloghuman.Sink(os.Stdout))
135 l.Debug(ctx, "testing1")
136 l.Info(ctx, "received request")
137
138 l = l.Leveled(slog.LevelDebug)
139
140 l.Debug(ctx, "testing2")
141
142
143
144 }
145
View as plain text