-
Notifications
You must be signed in to change notification settings - Fork 6
/
example_test.go
58 lines (46 loc) · 1.58 KB
/
example_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package clog_test
import (
"context"
"log/slog"
"os"
"github.com/chainguard-dev/clog"
"github.com/chainguard-dev/clog/slogtest"
)
func ExampleHandler() {
log := slog.New(clog.NewHandler(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
// Remove time for repeatable results
ReplaceAttr: slogtest.RemoveTime,
})))
ctx := context.Background()
ctx = clog.WithValues(ctx, "foo", "bar")
log.InfoContext(ctx, "hello world", slog.Bool("baz", true))
// Output:
// level=INFO msg="hello world" baz=true foo=bar
}
func ExampleLogger() {
log := clog.NewLogger(slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
// Remove time for repeatable results
ReplaceAttr: slogtest.RemoveTime,
})))
log = log.With("a", "b")
ctx := clog.WithLogger(context.Background(), log)
// Grab logger from context and use
// Note: this is a formatter aware method, not an slog.Attr method.
clog.FromContext(ctx).With("foo", "bar").Infof("hello %s", "world")
// Package level context loggers are also aware
clog.ErrorContext(ctx, "asdf", slog.Bool("baz", true))
// Output:
// level=INFO msg="hello world" a=b foo=bar
// level=ERROR msg=asdf a=b baz=true
}
func ExampleFromContext_preserveContext() {
log := clog.NewLogger(slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
// Remove time for repeatable results
ReplaceAttr: slogtest.RemoveTime,
}))).With("foo", "bar")
ctx := clog.WithLogger(context.Background(), log)
// Previous context values are preserved when using FromContext
clog.FromContext(ctx).Info("hello world")
// Output:
// level=INFO msg="hello world" foo=bar
}