-
Notifications
You must be signed in to change notification settings - Fork 8
/
slog.go
262 lines (224 loc) · 6.07 KB
/
slog.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
package slog
import (
"context"
"errors"
"log"
"log/slog"
"os"
"slices"
"sync"
"time"
"github.com/axiomhq/axiom-go/axiom"
"github.com/axiomhq/axiom-go/axiom/ingest"
)
var _ slog.Handler = (*Handler)(nil)
const defaultBatchSize = 10_000
// ErrMissingDatasetName is raised when a dataset name is not provided. Set it
// manually using the [SetDataset] option or export "AXIOM_DATASET".
var ErrMissingDatasetName = errors.New("missing dataset name")
// An Option modifies the behaviour of the Axiom handler.
type Option func(*Handler) error
// SetClient specifies the Axiom client to use for ingesting the logs.
func SetClient(client *axiom.Client) Option {
return func(h *Handler) error {
h.client = client
return nil
}
}
// SetClientOptions specifies the Axiom client options to pass to
// [axiom.NewClient] which is only called if no [axiom.Client] was specified by
// the [SetClient] option.
func SetClientOptions(options ...axiom.Option) Option {
return func(h *Handler) error {
h.clientOptions = options
return nil
}
}
// SetDataset specifies the dataset to ingest the logs into. Can also be
// specified using the "AXIOM_DATASET" environment variable.
func SetDataset(datasetName string) Option {
return func(h *Handler) error {
h.datasetName = datasetName
return nil
}
}
// SetIngestOptions specifies the ingestion options to use for ingesting the
// logs.
func SetIngestOptions(opts ...ingest.Option) Option {
return func(h *Handler) error {
h.ingestOptions = opts
return nil
}
}
// SetLevel specifies the log level the handler is enabled for.
func SetLevel(level slog.Leveler) Option {
return func(h *Handler) error {
h.level = level
return nil
}
}
type rootHandler struct {
client *axiom.Client
datasetName string
clientOptions []axiom.Option
ingestOptions []ingest.Option
eventCh chan axiom.Event
closeCh chan struct{}
closeOnce sync.Once
}
// Handler implements a [slog.Handler] used for shipping logs to Axiom.
type Handler struct {
*rootHandler
level slog.Leveler
attrs []slog.Attr
groups []string
}
// New creates a new handler that ingests logs into Axiom. It automatically
// takes its configuration from the environment. To connect, export the
// following environment variables:
//
// - AXIOM_TOKEN
// - AXIOM_ORG_ID (only when using a personal token)
// - AXIOM_DATASET
//
// The configuration can be set manually using options which are prefixed with
// "Set".
//
// An API token with "ingest" permission is sufficient enough.
//
// A handler needs to be closed properly to make sure all logs are sent by
// calling [Handler.Close].
func New(options ...Option) (*Handler, error) {
root := &rootHandler{
eventCh: make(chan axiom.Event, defaultBatchSize),
closeCh: make(chan struct{}),
}
handler := &Handler{
rootHandler: root,
}
// Apply supplied options.
for _, option := range options {
if option == nil {
continue
} else if err := option(handler); err != nil {
return nil, err
}
}
// Create client, if not set.
if root.client == nil {
var err error
if root.client, err = axiom.NewClient(root.clientOptions...); err != nil {
return nil, err
}
}
// When the dataset name is not set, use "AXIOM_DATASET".
if root.datasetName == "" {
root.datasetName = os.Getenv("AXIOM_DATASET")
if root.datasetName == "" {
return nil, ErrMissingDatasetName
}
}
// Run background ingest.
go func() {
defer close(root.closeCh)
logger := log.New(os.Stderr, "[AXIOM|SLOG]", 0)
res, err := root.client.IngestChannel(context.Background(), root.datasetName, root.eventCh, root.ingestOptions...)
if err != nil {
logger.Printf("failed to ingest events: %s\n", err)
} else if res.Failed > 0 {
// Best effort on notifying the user about the ingest failure.
logger.Printf("event at %s failed to ingest: %s\n",
res.Failures[0].Timestamp, res.Failures[0].Error)
}
}()
return handler, nil
}
// Close the handler and make sure all events are flushed. Closing the handler
// renders it unusable for further use.
func (h *Handler) Close() {
h.closeOnce.Do(func() {
close(h.eventCh)
<-h.closeCh
})
}
// Enabled implements [slog.Handler].
func (h *Handler) Enabled(_ context.Context, level slog.Level) bool {
minLevel := slog.LevelInfo
if h.level != nil {
minLevel = h.level.Level()
}
return level >= minLevel
}
// Handle implements [slog.Handler].
func (h *Handler) Handle(_ context.Context, r slog.Record) error {
event := axiom.Event{}
// Set handler attributes first, record attributes second.
for _, attr := range h.attrs {
addAttrToEvent(event, attr)
}
r.Attrs(func(attr slog.Attr) bool {
addAttrToEvent(event, attr)
return true
})
// Nest attributes in handler groups as objects, if any.
for i := len(h.groups) - 1; i >= 0; i-- {
event = axiom.Event{h.groups[i]: event}
}
// Set timestamp, level and actual message. The zero time is ignored.
if !r.Time.IsZero() {
event[ingest.TimestampField] = r.Time.Format(time.RFC3339Nano)
}
event[slog.LevelKey] = r.Level.String()
event[slog.MessageKey] = r.Message
select {
case <-h.closeCh:
return errors.New("handler closed")
default:
h.eventCh <- event
return nil
}
}
// WithAttrs implements [slog.Handler].
func (h *Handler) WithAttrs(attrs []slog.Attr) slog.Handler {
if len(attrs) == 0 {
return h
}
h2 := h.clone()
h2.attrs = append(h2.attrs, attrs...)
return h2
}
// WithGroup implements [slog.Handler].
func (h *Handler) WithGroup(name string) slog.Handler {
if name == "" {
return h
}
h2 := h.clone()
h2.groups = append(h2.groups, name)
return h2
}
func (h *Handler) clone() *Handler {
return &Handler{
rootHandler: h.rootHandler,
level: h.level,
attrs: slices.Clip(h.attrs),
groups: slices.Clip(h.groups),
}
}
func addAttrToEvent(event axiom.Event, attr slog.Attr) {
if attr.Equal(slog.Attr{}) {
return
}
// If we have a group, nest it as an object.
v := attr.Value.Resolve()
if v.Kind() == slog.KindGroup {
group := axiom.Event{}
for _, attr := range v.Group() {
addAttrToEvent(group, attr)
}
if len(group) > 0 && attr.Key != "" {
event[attr.Key] = group
}
} else {
event[attr.Key] = v.Any()
}
}