Repository navigation
Expand file tree
/
Copy pathhandler_test.go
More file actions
1969 lines (1548 loc) · 51.1 KB
/
Copy pathhandler_test.go
File metadata and controls
1969 lines (1548 loc) · 51.1 KB
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package slogseq
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"strings"
"sync"
"testing"
"testing/slogtest"
"time"
"github.com/stretchr/testify/require"
)
// A tiny payload that implements slog.LogValuer.
type payload struct {
ID int64
Name string
}
func (p payload) LogValue() slog.Value {
return slog.GroupValue(
slog.Int64("id", p.ID),
slog.String("name", p.Name),
)
}
type stubError struct{ msg string }
func (e stubError) Error() string { return e.msg }
// stringValuer implements slog.LogValuer returning a string (non-group) value.
type stringValuer string
func (s stringValuer) LogValue() slog.Value {
return slog.StringValue(string(s))
}
// Expectation: NewLogger should return a non-nil logger and handler.
func Test_NewLogger_ReturnsNonNil_Success(t *testing.T) {
t.Parallel()
logger, handler := NewLogger("http://fake", WithNoFlush())
defer handler.Close()
require.NotNil(t, logger)
require.NotNil(t, handler)
}
// Expectation: NewSeqHandler should return a non-nil handler with all defaults applied.
func Test_NewSeqHandler_Defaults_Success(t *testing.T) {
t.Parallel()
handler := NewSeqHandler("http://fake", WithNoFlush())
defer handler.Close()
require.NotNil(t, handler)
require.Equal(t, "http://fake", handler.seqURL)
require.Empty(t, handler.apiKey)
require.Equal(t, defaultBatchSize, handler.batchSize)
require.Equal(t, defaultBufferSize, handler.bufferSize)
require.Equal(t, defaultRetryBufferSize, handler.retryBufferSize)
require.Equal(t, defaultFlushInterval, handler.flushInterval)
require.Equal(t, defaultWorkerCount, handler.workerCount)
require.False(t, handler.blockingMode, "default should be non-blocking")
require.False(t, handler.disableTLSVerify)
require.Equal(t, slog.SourceKey, handler.sourceKey)
require.Nil(t, handler.options.Level)
require.Nil(t, handler.options.ReplaceAttr)
require.False(t, handler.options.AddSource)
}
// Expectation: NewSeqHandler should apply all provided options correctly.
func Test_NewSeqHandler_WithOptions_Success(t *testing.T) {
t.Parallel()
handler := NewSeqHandler("http://localhost:5341",
WithAPIKey("test-key"),
WithBatchSize(50),
WithFlushInterval(5*time.Second),
WithHandlerOptions(&slog.HandlerOptions{Level: slog.LevelWarn}),
)
defer handler.Close()
require.Equal(t, "http://localhost:5341", handler.seqURL)
require.Equal(t, "test-key", handler.apiKey)
require.Equal(t, 50, handler.batchSize)
require.Equal(t, 5*time.Second, handler.flushInterval)
require.Equal(t, slog.LevelWarn, handler.options.Level.Level())
}
// Expectation: start() should create workers with buffered channels.
func Test_start_CreatesWorkerChannels_Success(t *testing.T) {
t.Parallel()
_, handler := NewLogger("http://fake",
WithWorkers(3),
WithNoFlush(),
)
defer handler.Close()
require.Len(t, handler.workers, 3)
for i, w := range handler.workers {
require.NotNil(t, w.eventsCh, "worker %d should have a channel", i)
require.Equal(t, handler.bufferSize, cap(w.eventsCh), "worker %d channel capacity", i)
}
}
// Expectation: The default error handler should not panic when called.
func Test_start_DefaultErrorHandler_NoPanic_Success(t *testing.T) {
t.Parallel()
_, handler := NewLogger("http://fake",
WithHTTPClient(GetHTTPClientMock(500, "error", func() {})),
WithBatchSize(1),
WithFlushInterval(time.Millisecond),
// No WithErrorHandler - uses the default no-op.
)
logger := slog.New(handler)
logger.Info("trigger flush")
// Give the flusher time to attempt sending and hit the error path.
time.Sleep(50 * time.Millisecond)
require.NotPanics(t, func() {
_ = handler.Close()
})
}
// Expectation: The handler should pass the stdlib slogtest compliance suite.
func Test_SeqHandler_Slogtest_Compliance_Success(t *testing.T) {
t.Parallel()
var mu sync.Mutex
var captured []string
client := &http.Client{
Transport: &mockTransport{
RoundTripFunc: func(req *http.Request) (*http.Response, error) {
body, _ := io.ReadAll(req.Body)
mu.Lock()
for line := range strings.SplitSeq(strings.TrimSpace(string(body)), "\n") {
if line != "" {
captured = append(captured, line)
}
}
mu.Unlock()
return &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewReader(nil)),
}, nil
},
},
}
_, handler := NewLogger("http://fake",
WithHTTPClient(client),
WithBatchSize(1),
WithFlushInterval(time.Millisecond),
)
err := slogtest.TestHandler(handler, func() []map[string]any {
time.Sleep(50 * time.Millisecond)
_ = handler.Close()
mu.Lock()
defer mu.Unlock()
results := make([]map[string]any, 0, len(captured))
for _, line := range captured {
var m map[string]any
if err := json.Unmarshal([]byte(line), &m); err != nil {
t.Fatalf("failed to parse CLEF line: %v", err)
}
// slogtest expects standard keys
parsed := make(map[string]any)
for k, v := range m {
switch k {
case "@t":
// Slog specification expects zero times to be omitted, but
// CLEF specification requires even zero timestamps be sent.
// We do this little dance to satisfy the slog test suite...
if s, ok := v.(string); ok {
t, err := time.Parse(time.RFC3339Nano, s)
if err == nil && t.IsZero() {
break // Omit it for this test.
}
}
parsed["time"] = v
case "@m":
parsed["msg"] = v
case "@l":
parsed["level"] = v
default:
parsed[k] = v
}
}
results = append(results, parsed)
}
return results
})
require.NoError(t, err)
}
// Expectation: Debug and Info levels should be disabled when minimum level is Warn.
func Test_SeqHandler_Enabled_DebugDisabled_Success(t *testing.T) {
t.Parallel()
opts := &slog.HandlerOptions{Level: slog.LevelWarn}
_, handler := NewLogger("http://fake",
WithAPIKey(""),
WithBatchSize(10),
WithFlushInterval(5*time.Second),
WithHandlerOptions(opts),
)
defer handler.Close()
require.False(t, handler.Enabled(context.Background(), slog.LevelDebug))
require.False(t, handler.Enabled(context.Background(), slog.LevelInfo))
require.True(t, handler.Enabled(context.Background(), slog.LevelWarn))
require.True(t, handler.Enabled(context.Background(), slog.LevelError))
}
// Expectation: Enabled should return true for all levels when no Level option is set.
func Test_SeqHandler_Enabled_NilLevel_AllEnabled_Success(t *testing.T) {
t.Parallel()
_, handler := NewLogger("http://fake",
WithNoFlush(),
)
defer handler.Close()
require.True(t, handler.Enabled(context.Background(), slog.LevelDebug))
require.True(t, handler.Enabled(context.Background(), slog.LevelInfo))
require.True(t, handler.Enabled(context.Background(), slog.LevelWarn))
require.True(t, handler.Enabled(context.Background(), slog.LevelError))
}
// Expectation: Ping should return nil when the Seq server responds with 200 OK.
func Test_SeqHandler_Ping_ReturnsNil_Success(t *testing.T) {
t.Parallel()
client := GetHTTPClientMock(200, `{"status":"healthy"}`, func() {})
handler := NewSeqHandler("http://fake/ingest/clef",
WithHTTPClient(client),
WithNoFlush(),
)
defer handler.Close()
err := handler.Ping()
require.NoError(t, err)
}
// Expectation: Ping should return an error when the Seq server responds with 503.
func Test_SeqHandler_Ping_Returns503_Error(t *testing.T) {
t.Parallel()
client := GetHTTPClientMock(503, `{"status":"unavailable"}`, func() {})
handler := NewSeqHandler("http://fake/ingest/clef",
WithHTTPClient(client),
WithNoFlush(),
)
defer handler.Close()
err := handler.Ping()
require.Error(t, err)
require.Contains(t, err.Error(), "503")
}
// Expectation: Ping should return an error when the server is unreachable.
func Test_SeqHandler_Ping_Unreachable_Error(t *testing.T) {
t.Parallel()
client := &http.Client{
Transport: &mockTransport{
RoundTripFunc: func(*http.Request) (*http.Response, error) {
return nil, errors.New("dial tcp: connect: connection refused")
},
},
}
handler := NewSeqHandler("http://fake/ingest/clef",
WithHTTPClient(client),
WithNoFlush(),
)
defer handler.Close()
err := handler.Ping()
require.Error(t, err)
require.Contains(t, err.Error(), "health check")
}
// Expectation: Ping should derive /health from any ingestion path.
func Test_SeqHandler_Ping_DerivesHealthPath_Success(t *testing.T) {
t.Parallel()
var capturedPath string
client := &http.Client{
Transport: &mockTransport{
RoundTripFunc: func(req *http.Request) (*http.Response, error) {
capturedPath = req.URL.String()
return &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewReader(nil)),
}, nil
},
},
}
handler := NewSeqHandler("http://fake/ingest/clef",
WithHTTPClient(client),
WithNoFlush(),
)
defer handler.Close()
err := handler.Ping()
require.NoError(t, err)
require.Equal(t, "http://fake/health", capturedPath)
}
// Expectation: Ping should send the API key when one is configured.
func Test_SeqHandler_Ping_SendsAPIKey_Success(t *testing.T) {
t.Parallel()
var capturedKey string
client := &http.Client{
Transport: &mockTransport{
RoundTripFunc: func(req *http.Request) (*http.Response, error) {
capturedKey = req.Header.Get("X-Seq-ApiKey")
return &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewReader(nil)),
}, nil
},
},
}
handler := NewSeqHandler("http://fake/ingest/clef",
WithHTTPClient(client),
WithAPIKey("my-secret-key"),
WithNoFlush(),
)
defer handler.Close()
err := handler.Ping()
require.NoError(t, err)
require.Equal(t, "my-secret-key", capturedKey)
}
// Expectation: Ping should not send an API key header when none is configured.
func Test_SeqHandler_Ping_NoAPIKey_OmitsHeader_Success(t *testing.T) {
t.Parallel()
var hasHeader bool
client := &http.Client{
Transport: &mockTransport{
RoundTripFunc: func(req *http.Request) (*http.Response, error) {
hasHeader = req.Header.Get("X-Seq-ApiKey") != ""
return &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewReader(nil)),
}, nil
},
},
}
handler := NewSeqHandler("http://fake/ingest/clef",
WithHTTPClient(client),
WithNoFlush(),
)
defer handler.Close()
err := handler.Ping()
require.NoError(t, err)
require.False(t, hasHeader)
}
// Expectation: Ping should return an error when the URL is unparseable.
func Test_SeqHandler_Ping_InvalidURL_Error(t *testing.T) {
t.Parallel()
handler := NewSeqHandler("://bad-url",
WithNoFlush(),
)
defer handler.Close()
err := handler.Ping()
require.Error(t, err)
require.Contains(t, err.Error(), "seq URL")
}
// Expectation: Ping should strip query parameters from the URL.
func Test_SeqHandler_Ping_StripsQueryParams_Success(t *testing.T) {
t.Parallel()
var capturedRawQuery string
client := &http.Client{
Transport: &mockTransport{
RoundTripFunc: func(req *http.Request) (*http.Response, error) {
capturedRawQuery = req.URL.RawQuery
return &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewReader(nil)),
}, nil
},
},
}
handler := NewSeqHandler("http://fake/ingest/clef?token=abc",
WithHTTPClient(client),
WithNoFlush(),
)
defer handler.Close()
err := handler.Ping()
require.NoError(t, err)
require.Empty(t, capturedRawQuery)
}
// Expectation: Handle should return nil error on success.
func Test_SeqHandler_Handle_ReturnsNilError_Success(t *testing.T) {
t.Parallel()
_, handler := NewLogger("http://fake",
WithWorkers(1),
WithNoFlush(),
)
defer handler.Close()
r := slog.NewRecord(time.Now(), slog.LevelInfo, "test", 0)
err := handler.Handle(context.Background(), r)
require.NoError(t, err)
<-handler.Events(0) // drain
}
// Expectation: Handle should send events with the correct message, level, and properties.
func Test_SeqHandler_Handle_CorrectProperties_Success(t *testing.T) {
t.Parallel()
_, handler := NewLogger("http://fake",
WithAPIKey(""),
WithBatchSize(10),
WithFlushInterval(5*time.Second),
WithWorkers(1),
WithNoFlush(),
)
defer handler.Close()
logger := slog.New(handler)
logger.Info("Hello, slog-seq!", "user", "alice", "count", 123)
select {
case evt := <-handler.Events(0):
require.Equal(t, "Hello, slog-seq!", evt.Message)
require.Equal(t, "Information", evt.Level)
require.Equal(t, "alice", evt.Properties["user"])
require.Equal(t, int64(123), evt.Properties["count"].(int64))
case <-time.After(2000 * time.Millisecond):
t.Fatal("Timed out waiting for log event in eventsCh")
}
}
// Expectation: WithAttrs should merge attributes into subsequent log events.
func Test_SeqHandler_Handle_WithAttrs_MergesAttributes_Success(t *testing.T) {
t.Parallel()
_, handler := NewLogger("http://fake",
WithAPIKey(""),
WithBatchSize(10),
WithFlushInterval(5*time.Second),
WithWorkers(1),
WithNoFlush(),
)
defer handler.Close()
logger := slog.New(handler)
logger2 := logger.With("service", "testsvc")
logger2.Info("WithAttrs test", "version", "1.2.3")
select {
case evt := <-handler.Events(0):
require.Equal(t, "testsvc", evt.Properties["service"])
require.Equal(t, "1.2.3", evt.Properties["version"])
case <-time.After(2000 * time.Millisecond):
t.Fatal("Timed out waiting for WithAttrs event")
}
}
// Expectation: WithGroup should prefix attribute keys with the group name.
func Test_SeqHandler_Handle_WithGroup_PrefixesKeys_Success(t *testing.T) {
t.Parallel()
_, handler := NewLogger("http://fake",
WithAPIKey(""),
WithBatchSize(10),
WithFlushInterval(5*time.Second),
WithWorkers(1),
WithNoFlush(),
)
defer handler.Close()
logger := slog.New(handler)
grouped := logger.WithGroup("request").With("id", "1234").WithGroup("headers").With("Accept", "application/json")
grouped.Info("Grouped log")
select {
case evt := <-handler.Events(0):
request := evt.Properties["request"].(map[string]any)
headers := request["headers"].(map[string]any)
require.Equal(t, "1234", request["id"])
require.Equal(t, "application/json", headers["Accept"])
case <-time.After(2000 * time.Millisecond):
t.Fatal("Timed out waiting for grouped event")
}
}
// Expectation: LogValuer types should be resolved before being stored in properties.
func Test_SeqHandler_Handle_LogValuer_Resolved_Success(t *testing.T) {
t.Parallel()
_, handler := NewLogger("http://fake",
WithWorkers(1),
WithNoFlush(),
)
defer handler.Close()
logger := slog.New(handler)
logger.Info("valuer", "payload", payload{ID: 99, Name: "test"})
select {
case evt := <-handler.Events(0):
p := evt.Properties["payload"].(map[string]any)
require.Equal(t, int64(99), p["id"])
require.Equal(t, "test", p["name"])
case <-time.After(2 * time.Second):
t.Fatal("timed out waiting for event")
}
}
// Expectation: WithGroup as argument and as inline group should produce identical events.
func Test_SeqHandler_Handle_Grouping_ConsistentOutput_Success(t *testing.T) {
t.Parallel()
_, handler := NewLogger("http://fake",
WithAPIKey(""),
WithBatchSize(10),
WithFlushInterval(5*time.Second),
WithWorkers(1),
WithNoFlush(),
)
defer handler.Close()
ctx := context.Background()
logger := slog.New(handler)
logger.WithGroup("s").LogAttrs(ctx, slog.LevelInfo, "huba", slog.Int("a", 1), slog.Int("b", 2))
logger.LogAttrs(ctx, slog.LevelInfo, "huba", slog.Group("s", slog.Int("a", 1), slog.Int("b", 2)))
event1 := <-handler.Events(0)
event2 := <-handler.Events(0)
event1.Timestamp = event2.Timestamp
require.Equal(t, event1, event2)
}
// Expectation: Named groups should create nested maps, and same-key groups should merge.
func Test_SeqHandler_Handle_NamedGroupMerge_Success(t *testing.T) {
t.Parallel()
_, handler := NewLogger("http://fake",
WithWorkers(1),
WithNoFlush(),
)
defer handler.Close()
logger := slog.New(handler)
logger.Info("merge test",
slog.Group("db", slog.String("host", "localhost")),
slog.Group("db", slog.Int("port", 5432)),
)
select {
case evt := <-handler.Events(0):
db, ok := evt.Properties["db"].(map[string]any)
require.True(t, ok, "expected db to be a nested map")
require.Equal(t, "localhost", db["host"])
require.Equal(t, int64(5432), db["port"])
case <-time.After(2 * time.Second):
t.Fatal("timed out waiting for event")
}
}
// Expectation: ReplaceAttr should be able to redact sensitive attribute values.
func Test_SeqHandler_Handle_ReplaceAttr_RedactsPassword_Success(t *testing.T) {
t.Parallel()
opts := &slog.HandlerOptions{
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if a.Key == "password" {
a.Value = slog.StringValue("*****")
}
return a
},
}
_, handler := NewLogger("http://fake",
WithAPIKey(""),
WithBatchSize(10),
WithFlushInterval(5*time.Second),
WithWorkers(1),
WithHandlerOptions(opts),
WithNoFlush(),
)
defer handler.Close()
logger := slog.New(handler)
logger.Info("Super secret info", "password", "2Fat2Fly")
logger.WithGroup("secret_info").Info("Wohoo", "password", "secret")
event1 := <-handler.Events(0)
event2 := <-handler.Events(0)
require.Equal(t, "*****", event1.Properties["password"])
secretInfo := event2.Properties["secret_info"].(map[string]any)
require.Equal(t, "*****", secretInfo["password"])
}
// Expectation: ReplaceAttr returning an empty key should drop the attribute.
func Test_SeqHandler_Handle_ReplaceAttr_EmptyKey_DropsAttr_Success(t *testing.T) {
t.Parallel()
opts := &slog.HandlerOptions{
ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {
if a.Key == "secret" {
return slog.Attr{} // empty key = drop
}
return a
},
}
_, handler := NewLogger("http://fake",
WithWorkers(1),
WithHandlerOptions(opts),
WithNoFlush(),
)
defer handler.Close()
logger := slog.New(handler)
logger.Info("filtered", "secret", "hidden", "visible", "shown")
select {
case evt := <-handler.Events(0):
require.Nil(t, evt.Properties["secret"], "dropped attr should not appear")
require.Equal(t, "shown", evt.Properties["visible"])
case <-time.After(2 * time.Second):
t.Fatal("timed out waiting for event")
}
}
// Expectation: ReplaceAttr should receive the correct group scope for each attribute.
func Test_SeqHandler_Handle_ReplaceAttrGroupScope_CorrectGroups_Success(t *testing.T) {
t.Parallel()
var captured [][]string
opts := &slog.HandlerOptions{
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
captured = append(captured, append([]string{}, groups...))
return a
},
}
_, handler := NewLogger("http://fake",
WithWorkers(1),
WithHandlerOptions(opts),
WithNoFlush(),
)
defer handler.Close()
logger := slog.New(handler)
logger.With("a", 1).WithGroup("g").With("b", 2).Info("test", "c", 3)
<-handler.Events(0)
require.GreaterOrEqual(t, len(captured), 3, "expected at least 3 ReplaceAttr calls")
require.Empty(t, captured[0], "expected no groups for 'a'")
require.Equal(t, []string{"g"}, captured[1], "expected [g] for 'b'")
require.Equal(t, []string{"g"}, captured[2], "expected [g] for 'c'")
}
// Expectation: Anonymous groups should inline their attributes into the parent properties.
func Test_SeqHandler_Handle_AnonymousGroup_InlinesAttributes_Success(t *testing.T) {
t.Parallel()
_, handler := NewLogger("http://fake",
WithWorkers(1),
WithNoFlush(),
)
defer handler.Close()
logger := slog.New(handler)
logger.Info("anon-group",
slog.Any("", payload{ID: 42, Name: "keyname"}))
logger.With("", payload{ID: 42, Name: "keyname"}).
Info("anon-group")
evt1 := <-handler.Events(0)
evt2 := <-handler.Events(0)
require.Equal(t, int64(42), evt1.Properties["id"])
require.Equal(t, "keyname", evt1.Properties["name"])
require.Equal(t, int64(42), evt2.Properties["id"])
require.Equal(t, "keyname", evt2.Properties["name"])
evt1.Timestamp = evt2.Timestamp
require.Equal(t, evt1, evt2)
}
// Expectation: Source information should be added to log events when AddSource is enabled.
func Test_SeqHandler_Handle_AddSource_IncludesSourceInfo_Success(t *testing.T) {
t.Parallel()
_, handler := NewLogger("http://fake",
WithAPIKey(""),
WithBatchSize(10),
WithFlushInterval(5*time.Second),
WithSourceKey("gosource"),
WithHandlerOptions(&slog.HandlerOptions{AddSource: true}),
WithNoFlush(),
)
defer handler.Close()
logger := slog.New(handler)
logger.Info("Hello, slog-seq!", "user", "alice", "count", 123)
select {
case evt := <-handler.Events(0):
require.NotNil(t, evt.Properties["gosource"], "expected gosource to be set")
source := evt.Properties["gosource"].(*slog.Source)
require.NotEmpty(t, source.File)
require.NotZero(t, source.Line)
require.NotEmpty(t, source.Function)
require.Contains(t, source.Function, "Test_SeqHandler_Handle_AddSource_IncludesSourceInfo_Success")
case <-time.After(2000 * time.Millisecond):
t.Fatal("Timed out waiting for log event in eventsCh")
}
}
// Expectation: All events should be received across multiple workers.
func Test_SeqHandler_Handle_MultipleWorkers_AllEventsReceived_Success(t *testing.T) {
t.Parallel()
_, handler := NewLogger("http://fake",
WithWorkers(4),
WithNoFlush(),
)
defer handler.Close()
logger := slog.New(handler)
const n = 100
for i := range n {
logger.Info("event", "i", i)
}
total := 0
for w := range handler.workers {
drain:
for {
select {
case <-handler.Events(w):
total++
default:
break drain
}
}
}
require.Equal(t, n, total)
}
// Expectation: Events should be distributed across all workers, not concentrated on one.
func Test_SeqHandler_Handle_MultipleWorkers_EvenDistribution_Success(t *testing.T) {
t.Parallel()
_, handler := NewLogger("http://fake",
WithWorkers(4),
WithNoFlush(),
)
defer handler.Close()
logger := slog.New(handler)
const n = 1000
for i := range n {
logger.Info("event", "i", i)
}
counts := make([]int, len(handler.workers))
for w := range handler.workers {
for {
select {
case <-handler.Events(w):
counts[w]++
default:
goto next
}
}
next:
}
for w, c := range counts {
require.NotZero(t, c, "worker %d received no events", w)
}
}
// Expectation: Concurrent Handle calls should not lose any events.
func Test_SeqHandler_Handle_ConcurrentCalls_NoLostEvents_Success(t *testing.T) {
t.Parallel()
_, handler := NewLogger("http://fake",
WithWorkers(2),
WithNoFlush(),
)
defer handler.Close()
logger := slog.New(handler)
const goroutines = 10
const perGoroutine = 50
var wg sync.WaitGroup
wg.Add(goroutines)
for g := range goroutines {
go func(id int) {
defer wg.Done()
for i := range perGoroutine {
logger.Info("concurrent", "goroutine", id, "i", i)
}
}(g)
}
wg.Wait()
total := 0
for w := range handler.workers {
for {
select {
case <-handler.Events(w):
total++
default:
goto next
}
}
next:
}
expected := goroutines * perGoroutine
require.Equal(t, expected, total)
}
// Expectation: Concurrent WithAttrs, WithGroup, and Handle calls should not lose events.
func Test_SeqHandler_Handle_ConcurrentWithAttrsAndHandle_NoLostEvents_Success(t *testing.T) {
t.Parallel()
_, handler := NewLogger("http://fake",
WithWorkers(2),
WithNoFlush(),
)
defer handler.Close()
logger := slog.New(handler)
var wg sync.WaitGroup
wg.Add(3)
go func() {
defer wg.Done()
for i := range 50 {
logger.Info("base", "i", i)
}
}()
go func() {
defer wg.Done()
l := logger.With("service", "svc")
for i := range 50 {
l.Info("with-attrs", "i", i)
}
}()
go func() {
defer wg.Done()
l := logger.WithGroup("g").With("k", "v")
for i := range 50 {
l.Info("with-group", "i", i)
}
}()
wg.Wait()
total := 0
for w := range handler.workers {
for {
select {
case <-handler.Events(w):
total++
default:
goto next
}
}
next:
}
require.Equal(t, 150, total)
}
// Expectation: Non-blocking mode should drop events when the channel is full.
func Test_SeqHandler_Handle_NonBlocking_DropsOnFullChannel_Success(t *testing.T) {
t.Parallel()
_, handler := NewLogger("http://fake",
WithWorkers(1),
WithNoFlush(),
)
defer handler.Close()
logger := slog.New(handler)
for i := range handler.bufferSize + 500 {
logger.Info("flood", "i", i)
}
count := 0
for {
select {
case <-handler.Events(0):
count++
default:
goto done
}
}
done:
require.LessOrEqual(t, count, handler.bufferSize)
require.NotZero(t, count, "expected some events to be received")
}
// Expectation: Multi-line messages should split into message (first line) and exception (rest).
func Test_SeqHandler_Handle_MultilineMessage_SplitsException_Success(t *testing.T) {
t.Parallel()
_, handler := NewLogger("http://fake",
WithWorkers(1),
WithNoFlush(),
)
defer handler.Close()
logger := slog.New(handler)
logger.Info("first line\nsecond line\nthird line")
select {
case evt := <-handler.Events(0):
require.Equal(t, "first line", evt.Message)
require.Equal(t, "second line\nthird line", evt.Exception)
case <-time.After(2 * time.Second):
t.Fatal("timed out waiting for event")
}