@@ -16,6 +16,7 @@ This document is maintained by Jonathan Amsterdam `
[email protected] `.
16
16
1. [The `WithGroup` method](#the-`withgroup`-method)
17
17
1. [Testing](#testing)
18
18
1 . [ General considerations] ( #general-considerations )
19
+ 1. [Copying records](#copying-records)
19
20
1. [Concurrency safety](#concurrency-safety)
20
21
1. [Robustness](#robustness)
21
22
1. [Speed](#speed)
@@ -766,7 +767,44 @@ in 65 lines.
766
767
767
768
# General considerations
768
769
769
- TODO(jba): reintroduce the material on Record.Clone that used to be here.
770
+ ## Copying records
771
+
772
+ Most handlers won't need to copy the ` slog.Record ` that is passed
773
+ to the ` Handle ` method.
774
+ Those that do must take special care in some cases.
775
+
776
+ A handler can make a single copy of a ` Record ` with an ordinary Go
777
+ assignment, channel send or function call if it doesn't retain the
778
+ original.
779
+ But if its actions result in more than one copy, it should call ` Record.Clone `
780
+ to make the copies so that they don't share state.
781
+ This ` Handle ` method passes the record to a single handler, so it doesn't require ` Clone ` :
782
+
783
+ type Handler1 struct {
784
+ h slog.Handler
785
+ // ...
786
+ }
787
+
788
+ func (h *Handler1) Handle(ctx context.Context, r slog.Record) error {
789
+ return h.h.Handle(ctx, r)
790
+ }
791
+
792
+ This ` Handle ` method might pass the record to more than one handler, so it
793
+ should use ` Clone ` :
794
+
795
+ type Handler2 struct {
796
+ hs []slog.Handler
797
+ // ...
798
+ }
799
+
800
+ func (h *Handler2) Handle(ctx context.Context, r slog.Record) error {
801
+ for _, hh := range h.hs {
802
+ if err := hh.Handle(ctx, r.Clone()); err != nil {
803
+ return err
804
+ }
805
+ }
806
+ return nil
807
+ }
770
808
771
809
## Concurrency safety
772
810
0 commit comments