Repository navigation
Expand file tree
/
Copy pathexample_logsrv_test.go
More file actions
69 lines (53 loc) · 1.7 KB
/
Copy pathexample_logsrv_test.go
File metadata and controls
69 lines (53 loc) · 1.7 KB
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
59
60
61
62
63
64
65
66
67
68
69
package logsrv_test
import (
"bytes"
"fmt"
"log/slog"
"github.com/tecnickcom/nurago/pkg/logsrv"
"github.com/tecnickcom/nurago/pkg/logutil"
"github.com/tecnickcom/nurago/pkg/testutil"
)
func ExampleNewLogger() {
// A real service writes to os.Stderr. The buffer keeps the example
// output inspectable.
var buf bytes.Buffer
cfg, err := logutil.NewConfig(
logutil.WithOutWriter(&buf),
logutil.WithFormatStr("json"),
logutil.WithLevelStr("info"),
)
if err != nil {
fmt.Println(err)
return
}
// The returned logger is a standard *slog.Logger, so application code
// depends only on log/slog and never on zerolog.
logger := logsrv.NewLogger(cfg)
logger.Info("user logged in", "user", "alice")
logger.Debug("not emitted, below the configured level")
// The timestamp is replaced so the example output is deterministic.
fmt.Print(testutil.ReplaceDateTime(buf.String(), "TIME"))
// Output:
// {"level":"info","time":"TIME","user":"alice","trace_id":"","message":"user logged in"}
}
func ExampleNewHandler() {
var buf bytes.Buffer
cfg, err := logutil.NewConfig(
logutil.WithOutWriter(&buf),
logutil.WithFormatStr("json"),
logutil.WithLevelStr("warning"),
)
if err != nil {
fmt.Println(err)
return
}
// NewHandler returns the slog.Handler on its own, for wrapping with
// other handlers or for calling slog.New at the call site.
handler := logsrv.NewHandler(cfg)
logger := slog.New(handler)
logger.Warn("disk usage above threshold", "percent", 91)
logger.Info("not emitted, below the configured level")
fmt.Print(testutil.ReplaceDateTime(buf.String(), "TIME"))
// Output:
// {"level":"warning","time":"TIME","percent":91,"trace_id":"","message":"disk usage above threshold"}
}