File tree Expand file tree Collapse file tree 2 files changed +66
-0
lines changed
examples/slog/16.discard-handler Expand file tree Collapse file tree 2 files changed +66
-0
lines changed Original file line number Diff line number Diff line change 1+ # https://taskfile.dev
2+
3+ version : " 3"
4+
5+ tasks :
6+ default :
7+ cmds :
8+ - task : run
9+ run :
10+ cmds :
11+ - go run main.go -discard=false
12+ - go run main.go -discard=true
Original file line number Diff line number Diff line change 1+ package main
2+
3+ import (
4+ "flag"
5+ "log/slog"
6+ "os"
7+ )
8+
9+ func main () {
10+ discard := flag .Bool ("discard" , false , "Use slog.DiscardHandler" )
11+ flag .Parse ()
12+
13+ if err := run (* discard ); err != nil {
14+ panic (err )
15+ }
16+ }
17+
18+ func run (discard bool ) error {
19+ //
20+ // Go 1.24 にて、slog.DiscardHandler が追加された。
21+ // io.Discard と同様に、このハンドラは出力を行わない。
22+ //
23+ // > DiscardHandler discards all log output. DiscardHandler.Enabled returns false for all Levels.
24+ // > (DiscardHandler は、すべてのログ出力を破棄します。DiscardHandler.Enabled は、すべての Levels に対して false を返します。)
25+ //
26+ // # REFERENCES
27+ // - https://pkg.go.dev/log/slog#example-package-DiscardHandler
28+ //
29+ var (
30+ l = slog .New (handler (discard ))
31+ )
32+
33+ l .Info ("helloworld" )
34+ l .Warn ("helloworld" )
35+ l .Error ("helloworld" )
36+
37+ return nil
38+ }
39+
40+ func handler (discard bool ) slog.Handler {
41+ if discard {
42+ return slog .DiscardHandler
43+ }
44+
45+ return slog .NewTextHandler (os .Stdout , & slog.HandlerOptions {ReplaceAttr : rmTime })
46+ }
47+
48+ // From https://cs.opensource.google/go/go/+/refs/tags/go1.24.0:src/log/slog/internal/slogtest/slogtest.go;l=13
49+ func rmTime (groups []string , a slog.Attr ) slog.Attr {
50+ if a .Key == slog .TimeKey && len (groups ) == 0 {
51+ return slog.Attr {}
52+ }
53+ return a
54+ }
You can’t perform that action at this time.
0 commit comments