Handle formats the slog.Record argument as JSON object and adds it to the batch queue. If the batch queue threshold has been reached, the WriteFunc option is invoked with the accumulated logs which in turn will reset the batch queue.
(ctx context.Context, r slog.Record)
| 130 | // If the batch queue threshold has been reached, the WriteFunc option |
| 131 | // is invoked with the accumulated logs which in turn will reset the batch queue. |
| 132 | func (h *BatchHandler) Handle(ctx context.Context, r slog.Record) error { |
| 133 | if h.group != "" { |
| 134 | h.mux.Lock() |
| 135 | attrs := make([]any, 0, len(h.attrs)+r.NumAttrs()) |
| 136 | for _, a := range h.attrs { |
| 137 | attrs = append(attrs, a) |
| 138 | } |
| 139 | h.mux.Unlock() |
| 140 | |
| 141 | r.Attrs(func(a slog.Attr) bool { |
| 142 | attrs = append(attrs, a) |
| 143 | return true |
| 144 | }) |
| 145 | |
| 146 | r = slog.NewRecord(r.Time, r.Level, r.Message, r.PC) |
| 147 | r.AddAttrs(slog.Group(h.group, attrs...)) |
| 148 | } else if len(h.attrs) > 0 { |
| 149 | r = r.Clone() |
| 150 | |
| 151 | h.mux.Lock() |
| 152 | r.AddAttrs(h.attrs...) |
| 153 | h.mux.Unlock() |
| 154 | } |
| 155 | |
| 156 | if h.parent != nil { |
| 157 | return h.parent.Handle(ctx, r) |
| 158 | } |
| 159 | |
| 160 | data := make(map[string]any, r.NumAttrs()) |
| 161 | |
| 162 | r.Attrs(func(a slog.Attr) bool { |
| 163 | if err := h.resolveAttr(data, a); err != nil { |
| 164 | return false |
| 165 | } |
| 166 | return true |
| 167 | }) |
| 168 | |
| 169 | log := &Log{ |
| 170 | Time: r.Time, |
| 171 | Level: r.Level, |
| 172 | Message: r.Message, |
| 173 | Data: types.JSONMap[any](data), |
| 174 | } |
| 175 | |
| 176 | if h.options.BeforeAddFunc != nil && !h.options.BeforeAddFunc(ctx, log) { |
| 177 | return nil |
| 178 | } |
| 179 | |
| 180 | h.mux.Lock() |
| 181 | h.logs = append(h.logs, log) |
| 182 | totalLogs := len(h.logs) |
| 183 | h.mux.Unlock() |
| 184 | |
| 185 | if totalLogs >= h.options.BatchSize { |
| 186 | if err := h.WriteAll(ctx); err != nil { |
| 187 | return err |
| 188 | } |
| 189 | } |