|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "log/slog" |
| 6 | + "os" |
| 7 | + "runtime" |
| 8 | + "strconv" |
| 9 | + "sync" |
| 10 | + "time" |
| 11 | +) |
| 12 | + |
| 13 | +type ( |
| 14 | + counterHandler struct { |
| 15 | + slog.Handler |
| 16 | + count *int |
| 17 | + mu *sync.Mutex |
| 18 | + } |
| 19 | +) |
| 20 | + |
| 21 | +func newHandler(handler slog.Handler) *counterHandler { |
| 22 | + var ( |
| 23 | + count = 0 |
| 24 | + mu sync.Mutex |
| 25 | + ) |
| 26 | + return &counterHandler{Handler: handler, count: &count, mu: &mu} |
| 27 | +} |
| 28 | + |
| 29 | +func (me *counterHandler) Handle(ctx context.Context, r slog.Record) error { |
| 30 | + me.mu.Lock() |
| 31 | + defer me.mu.Unlock() |
| 32 | + |
| 33 | + r.AddAttrs(slog.String("millis", time.Now().Format(".000"))) |
| 34 | + r.AddAttrs(slog.Int("count", *me.count)) |
| 35 | + *me.count++ |
| 36 | + |
| 37 | + return me.Handler.Handle(ctx, r) |
| 38 | +} |
| 39 | + |
| 40 | +func (me *counterHandler) WithAttrs(attrs []slog.Attr) slog.Handler { |
| 41 | + return &counterHandler{Handler: me.Handler.WithAttrs(attrs), count: me.count, mu: me.mu} |
| 42 | +} |
| 43 | + |
| 44 | +func (me *counterHandler) WithGroup(name string) slog.Handler { |
| 45 | + return &counterHandler{Handler: me.Handler.WithGroup(name), count: me.count, mu: me.mu} |
| 46 | +} |
| 47 | + |
| 48 | +func main() { |
| 49 | + var ( |
| 50 | + level = &slog.LevelVar{} |
| 51 | + opt = &slog.HandlerOptions{ |
| 52 | + Level: level, |
| 53 | + ReplaceAttr: replaceAttr, |
| 54 | + } |
| 55 | + writer = os.Stdout |
| 56 | + handler = newHandler(slog.NewTextHandler(writer, opt)) |
| 57 | + logger = slog.New(handler) |
| 58 | + |
| 59 | + wg sync.WaitGroup |
| 60 | + goroutineCount = runtime.NumCPU() * 2 |
| 61 | + loopCount = 2 |
| 62 | + ) |
| 63 | + |
| 64 | + logger.Info("Start", "NumCPU", runtime.NumCPU(), "goroutineCount", goroutineCount) |
| 65 | + |
| 66 | + wg.Add(goroutineCount) |
| 67 | + for i := range goroutineCount { |
| 68 | + go func(logger *slog.Logger) { |
| 69 | + defer wg.Done() |
| 70 | + for i := range loopCount { |
| 71 | + logger.Info(strconv.Itoa(i)) |
| 72 | + } |
| 73 | + }(logger.With("goroutine", i)) |
| 74 | + } |
| 75 | + |
| 76 | + wg.Wait() |
| 77 | +} |
| 78 | + |
| 79 | +func replaceAttr(g []string, a slog.Attr) slog.Attr { |
| 80 | + if a.Key == slog.TimeKey { |
| 81 | + return slog.Attr{} |
| 82 | + } |
| 83 | + |
| 84 | + return a |
| 85 | +} |
0 commit comments