Source file
src/log/slog/example_custom_levels_test.go
1
2
3
4
5 package slog_test
6
7 import (
8 "context"
9 "log/slog"
10 "os"
11 )
12
13
14
15
16
17 func ExampleHandlerOptions_customLevels() {
18
19 const (
20 LevelTrace = slog.Level(-8)
21 LevelDebug = slog.LevelDebug
22 LevelInfo = slog.LevelInfo
23 LevelNotice = slog.Level(2)
24 LevelWarning = slog.LevelWarn
25 LevelError = slog.LevelError
26 LevelEmergency = slog.Level(12)
27 )
28
29 th := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
30
31
32 Level: LevelTrace,
33
34 ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
35
36 if a.Key == slog.TimeKey {
37 return slog.Attr{}
38 }
39
40
41
42 if a.Key == slog.LevelKey {
43
44 a.Key = "sev"
45
46
47 level := a.Value.Any().(slog.Level)
48
49
50
51
52
53 switch {
54 case level < LevelDebug:
55 a.Value = slog.StringValue("TRACE")
56 case level < LevelInfo:
57 a.Value = slog.StringValue("DEBUG")
58 case level < LevelNotice:
59 a.Value = slog.StringValue("INFO")
60 case level < LevelWarning:
61 a.Value = slog.StringValue("NOTICE")
62 case level < LevelError:
63 a.Value = slog.StringValue("WARNING")
64 case level < LevelEmergency:
65 a.Value = slog.StringValue("ERROR")
66 default:
67 a.Value = slog.StringValue("EMERGENCY")
68 }
69 }
70
71 return a
72 },
73 })
74
75 logger := slog.New(th)
76 ctx := context.Background()
77 logger.Log(ctx, LevelEmergency, "missing pilots")
78 logger.Error("failed to start engines", "err", "missing fuel")
79 logger.Warn("falling back to default value")
80 logger.Log(ctx, LevelNotice, "all systems are running")
81 logger.Info("initiating launch")
82 logger.Debug("starting background job")
83 logger.Log(ctx, LevelTrace, "button clicked")
84
85
86
87
88
89
90
91
92
93 }
94
View as plain text