-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsampling_test.go
More file actions
2358 lines (1970 loc) · 70.6 KB
/
sampling_test.go
File metadata and controls
2358 lines (1970 loc) · 70.6 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 mtlog
import (
"fmt"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/willibrandon/mtlog/core"
"github.com/willibrandon/mtlog/internal/filters"
"github.com/willibrandon/mtlog/sinks"
)
// TestSampleEveryNth tests the Sample method for every nth message sampling
func TestSampleEveryNth(t *testing.T) {
sink := sinks.NewMemorySink()
logger := New(WithSink(sink))
// Sample every 3rd message
sampledLogger := logger.Sample(3)
// Log 10 messages
for i := 1; i <= 10; i++ {
sampledLogger.Info("Message {Number}", i)
}
// Should have logged messages 1, 4, 7, 10 (every 3rd starting from 1)
events := sink.Events()
expectedCount := 4
if len(events) != expectedCount {
t.Errorf("Expected %d events, got %d", expectedCount, len(events))
}
// Verify the logged message numbers
expectedNumbers := []int{1, 4, 7, 10}
for i, event := range events {
if num, ok := event.Properties["Number"].(int); ok {
if num != expectedNumbers[i] {
t.Errorf("Expected message %d, got %d", expectedNumbers[i], num)
}
}
}
}
// TestSampleRate tests the SampleRate method for percentage-based sampling
func TestSampleRate(t *testing.T) {
sink := sinks.NewMemorySink()
logger := New(WithSink(sink))
// Sample 30% of messages for more reliable testing
sampledLogger := logger.SampleRate(0.3)
// Log 200 messages for better statistical reliability
for i := 1; i <= 200; i++ {
sampledLogger.Info("Message {Number}", i)
}
events := sink.Events()
// With 30% sampling of 200 messages, we expect around 60 messages
// Allow very wide variance due to true random sampling (especially on Windows)
if len(events) < 30 || len(events) > 90 {
t.Errorf("Expected around 60 events (30-90 range for random sampling), got %d", len(events))
}
}
// TestSampleDuration tests the SampleDuration method for time-based sampling
func TestSampleDuration(t *testing.T) {
sink := sinks.NewMemorySink()
logger := New(WithSink(sink))
// Sample at most once per 100ms
sampledLogger := logger.SampleDuration(100 * time.Millisecond)
// Log messages rapidly
for i := 1; i <= 10; i++ {
sampledLogger.Info("Message {Number}", i)
time.Sleep(10 * time.Millisecond)
}
events := sink.Events()
// Should have logged first message and maybe 1 more after 100ms
if len(events) < 1 || len(events) > 2 {
t.Errorf("Expected 1-2 events with 100ms duration sampling, got %d", len(events))
}
}
// TestSampleFirst tests the SampleFirst method for logging only first N occurrences
func TestSampleFirst(t *testing.T) {
sink := sinks.NewMemorySink()
logger := New(WithSink(sink))
// Log only first 5 messages
sampledLogger := logger.SampleFirst(5)
// Try to log 10 messages
for i := 1; i <= 10; i++ {
sampledLogger.Info("Message {Number}", i)
}
events := sink.Events()
if len(events) != 5 {
t.Errorf("Expected exactly 5 events, got %d", len(events))
}
// Verify it's the first 5 messages
for i, event := range events {
if num, ok := event.Properties["Number"].(int); ok {
if num != i+1 {
t.Errorf("Expected message %d, got %d", i+1, num)
}
}
}
}
// TestSampleGroup tests the SampleGroup method for grouped sampling
func TestSampleGroup(t *testing.T) {
sink := sinks.NewMemorySink()
logger := New(WithSink(sink))
// Create two loggers sampling in the same group
logger1 := logger.SampleGroup("test-group", 3)
logger2 := logger.SampleGroup("test-group", 3)
// Log from both loggers - they should share the counter
for i := 1; i <= 5; i++ {
logger1.Info("Logger1 message {Number}", i)
logger2.Info("Logger2 message {Number}", i)
}
events := sink.Events()
// With shared counter and sampling every 3rd:
// Messages 1, 4, 7, 10 should be logged (out of 10 total)
expectedCount := 4
if len(events) != expectedCount {
t.Errorf("Expected %d events with shared group counter, got %d", expectedCount, len(events))
}
}
// TestSampleWhen tests the SampleWhen method for conditional sampling
func TestSampleWhen(t *testing.T) {
sink := sinks.NewMemorySink()
logger := New(WithSink(sink))
// Track a condition
var highLoad atomic.Bool
highLoad.Store(false)
// Sample every 2nd message when high load
sampledLogger := logger.SampleWhen(func() bool {
return highLoad.Load()
}, 2)
// Log with condition false
for i := 1; i <= 3; i++ {
sampledLogger.Info("Low load message {Number}", i)
}
// Enable condition
highLoad.Store(true)
// Log with condition true
for i := 4; i <= 8; i++ {
sampledLogger.Info("High load message {Number}", i)
}
events := sink.Events()
// Should have 0 from low load, and messages 4, 6, 8 from high load
expectedCount := 3
if len(events) != expectedCount {
t.Errorf("Expected %d events with conditional sampling, got %d", expectedCount, len(events))
}
}
// TestSampleBackoff tests the SampleBackoff method for exponential backoff
func TestSampleBackoff(t *testing.T) {
sink := sinks.NewMemorySink()
logger := New(WithSink(sink))
// Sample with exponential backoff (factor 2)
sampledLogger := logger.SampleBackoff("error-key", 2.0)
// Log 20 messages
for i := 1; i <= 20; i++ {
sampledLogger.Error("Error {Number}", i)
}
events := sink.Events()
// With factor 2.0, should log messages at positions: 1, 2, 4, 8, 16
expectedCount := 5
if len(events) != expectedCount {
t.Errorf("Expected %d events with exponential backoff, got %d", expectedCount, len(events))
}
// Verify the logged positions
expectedNumbers := []int{1, 2, 4, 8, 16}
for i, event := range events {
if num, ok := event.Properties["Number"].(int); ok {
if num != expectedNumbers[i] {
t.Errorf("Expected message at position %d, got %d", expectedNumbers[i], num)
}
}
}
}
// TestResetSampling tests the ResetSampling method
func TestResetSampling(t *testing.T) {
sink := sinks.NewMemorySink()
logger := New(WithSink(sink))
// Sample every 3rd message
sampledLogger := logger.Sample(3)
// Log 3 messages
for i := 1; i <= 3; i++ {
sampledLogger.Info("First batch {Number}", i)
}
// Reset the sampling counter
sampledLogger.ResetSampling()
// Log 3 more messages
for i := 4; i <= 6; i++ {
sampledLogger.Info("Second batch {Number}", i)
}
events := sink.Events()
// Should have messages 1 from first batch and 4 from second batch (after reset)
expectedCount := 2
if len(events) != expectedCount {
t.Errorf("Expected %d events after reset, got %d", expectedCount, len(events))
}
}
// TestResetSamplingGroup tests the ResetSamplingGroup method
func TestResetSamplingGroup(t *testing.T) {
sink := sinks.NewMemorySink()
logger := New(WithSink(sink))
// Create logger with group sampling
sampledLogger := logger.SampleGroup("reset-test", 3)
// Log 3 messages
for i := 1; i <= 3; i++ {
sampledLogger.Info("First batch {Number}", i)
}
// Reset the group counter
sampledLogger.ResetSamplingGroup("reset-test")
// Log 3 more messages
for i := 4; i <= 6; i++ {
sampledLogger.Info("Second batch {Number}", i)
}
events := sink.Events()
// Should have messages 1 from first batch and 4 from second batch (after reset)
expectedCount := 2
if len(events) != expectedCount {
t.Errorf("Expected %d events after group reset, got %d", expectedCount, len(events))
}
}
// TestSamplingWithLevels tests that sampling works with different log levels
func TestSamplingWithLevels(t *testing.T) {
sink := sinks.NewMemorySink()
logger := New(
WithSink(sink),
WithMinimumLevel(core.InformationLevel),
)
// Sample every 2nd message
sampledLogger := logger.Sample(2)
// Log at different levels
sampledLogger.Debug("Debug 1") // Below minimum level
sampledLogger.Info("Info 1") // Sampled (1st)
sampledLogger.Info("Info 2") // Not sampled
sampledLogger.Warning("Warning 1") // Sampled (3rd)
sampledLogger.Error("Error 1") // Not sampled (4th)
sampledLogger.Error("Error 2") // Sampled (5th)
events := sink.Events()
// Debug is filtered by level, others follow sampling pattern
expectedCount := 3 // Info 1, Warning 1, Error 2
if len(events) != expectedCount {
t.Errorf("Expected %d events with level filtering and sampling, got %d", expectedCount, len(events))
}
}
// TestConcurrentSampling tests thread safety of sampling
func TestConcurrentSampling(t *testing.T) {
sink := sinks.NewMemorySink()
logger := New(WithSink(sink))
// Sample every 10th message
sampledLogger := logger.Sample(10)
// Log concurrently from multiple goroutines
var wg sync.WaitGroup
numGoroutines := 10
messagesPerGoroutine := 100
for g := 0; g < numGoroutines; g++ {
wg.Add(1)
go func(goroutineID int) {
defer wg.Done()
for i := 0; i < messagesPerGoroutine; i++ {
sampledLogger.Info("Message from goroutine {GoroutineID} iteration {Iteration}",
goroutineID, i)
}
}(g)
}
wg.Wait()
events := sink.Events()
totalMessages := numGoroutines * messagesPerGoroutine
expectedCount := totalMessages / 10
// Allow some variance for concurrent execution
if len(events) < expectedCount-1 || len(events) > expectedCount+1 {
t.Errorf("Expected around %d events with concurrent sampling, got %d",
expectedCount, len(events))
}
}
// TestChainedSampling tests chaining multiple sampling methods
func TestChainedSampling(t *testing.T) {
sink := sinks.NewMemorySink()
logger := New(WithSink(sink))
// Create two separate sampling loggers from the base logger
sampled1 := logger.Sample(2) // Every 2nd
sampled2 := logger.Sample(3) // Every 3rd (independent counter)
// Log 10 messages with each logger
for i := 1; i <= 10; i++ {
sampled1.Info("Logger1 message {Number}", i)
sampled2.Info("Logger2 message {Number}", i)
}
events := sink.Events()
// sampled1 logs every 2nd: 1, 3, 5, 7, 9 (5 messages)
// sampled2 logs every 3rd: 1, 4, 7, 10 (4 messages)
// Total: 9 messages
expectedCount := 9
if len(events) != expectedCount {
t.Errorf("Expected %d events with two sampling loggers, got %d", expectedCount, len(events))
}
// Test that chaining adds filters cumulatively (both filters apply)
sink2 := sinks.NewMemorySink()
logger2 := New(WithSink(sink2))
// Chain sampling - both filters apply cumulatively
chainedLogger := logger2.Sample(2).Sample(3)
// Log 20 messages to see the pattern
for i := 1; i <= 20; i++ {
chainedLogger.Info("Chained message {Number}", i)
}
events2 := sink2.Events()
// With both filters applied cumulatively:
// First filter passes every 2nd: 1, 3, 5, 7, 9, 11, 13, 15, 17, 19
// Second filter passes every 3rd: 1, 7, 13, 19
expectedChainedCount := 4
if len(events2) != expectedChainedCount {
t.Errorf("Expected %d events with chained sampling, got %d",
expectedChainedCount, len(events2))
}
// Verify the specific message numbers
expectedChainedNumbers := []int{1, 7, 13, 19}
for i, event := range events2 {
if num, ok := event.Properties["Number"].(int); ok {
if num != expectedChainedNumbers[i] {
t.Errorf("Expected chained message %d, got %d", expectedChainedNumbers[i], num)
}
}
}
}
// TestWithDefaultSampling tests the WithDefaultSampling configuration option
func TestWithDefaultSampling(t *testing.T) {
sink := sinks.NewMemorySink()
logger := New(
WithSink(sink),
WithDefaultSampling(3), // Sample every 3rd message by default
)
// Log 10 messages
for i := 1; i <= 10; i++ {
logger.Info("Message {Number}", i)
}
events := sink.Events()
// Should sample every 3rd: 1, 4, 7, 10
expectedCount := 4
if len(events) != expectedCount {
t.Errorf("Expected %d events with default sampling, got %d", expectedCount, len(events))
}
}
// TestSampleRateEdgeCases tests edge cases for rate sampling
func TestSampleRateEdgeCases(t *testing.T) {
tests := []struct {
name string
rate float32
messageCount int
expectedCount int
}{
{"Rate 0.0", 0.0, 10, 0},
{"Rate 1.0", 1.0, 10, 10},
{"Rate -0.5 (clamped to 0)", -0.5, 10, 0},
{"Rate 1.5 (clamped to 1)", 1.5, 10, 10},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
sink := sinks.NewMemorySink()
logger := New(WithSink(sink))
sampledLogger := logger.SampleRate(tt.rate)
for i := 1; i <= tt.messageCount; i++ {
sampledLogger.Info("Message {Number}", i)
}
events := sink.Events()
if len(events) != tt.expectedCount {
t.Errorf("Expected %d events with rate %f, got %d",
tt.expectedCount, tt.rate, len(events))
}
})
}
}
// TestSampleFirstZero tests SampleFirst with n=0
func TestSampleFirstZero(t *testing.T) {
sink := sinks.NewMemorySink()
logger := New(WithSink(sink))
// Log zero messages
sampledLogger := logger.SampleFirst(0)
// Try to log messages
for i := 1; i <= 5; i++ {
sampledLogger.Info("Message {Number}", i)
}
events := sink.Events()
if len(events) != 0 {
t.Errorf("Expected 0 events with SampleFirst(0), got %d", len(events))
}
}
// TestConcurrentGroupSampling tests concurrent access to shared group counters
func TestConcurrentGroupSampling(t *testing.T) {
sink := sinks.NewMemorySink()
logger := New(WithSink(sink))
const numGoroutines = 20
const messagesPerGoroutine = 100
const samplingFactor = 10
const groupName = "concurrent-test"
var wg sync.WaitGroup
// Launch multiple goroutines, each with their own logger sharing the same group
for g := 0; g < numGoroutines; g++ {
wg.Add(1)
go func(goroutineID int) {
defer wg.Done()
// Each goroutine gets its own logger but sharing the same group
groupLogger := logger.SampleGroup(groupName, samplingFactor)
for i := 0; i < messagesPerGoroutine; i++ {
groupLogger.Info("Message from goroutine {GoroutineID} iteration {Iteration}",
goroutineID, i)
}
}(g)
}
wg.Wait()
events := sink.Events()
totalMessages := numGoroutines * messagesPerGoroutine
expectedCount := totalMessages / samplingFactor
// Allow variance due to the atomic nature of concurrent operations
// In concurrent scenarios, the exact count may vary slightly
tolerance := 2
if len(events) < expectedCount-tolerance || len(events) > expectedCount+tolerance {
t.Errorf("Expected approximately %d events (±%d), got %d from %d total messages",
expectedCount, tolerance, len(events), totalMessages)
}
// Verify that we got messages from multiple goroutines
goroutineMap := make(map[int]bool)
for _, event := range events {
if gid, ok := event.Properties["GoroutineID"].(int); ok {
goroutineMap[gid] = true
}
}
// Should have messages from multiple goroutines (though not necessarily all)
if len(goroutineMap) < 2 {
t.Errorf("Expected messages from multiple goroutines, got from %d goroutines", len(goroutineMap))
}
}
// TestConcurrentGroupCounterStress stress tests the group counter under extreme load
func TestConcurrentGroupCounterStress(t *testing.T) {
sink := sinks.NewMemorySink()
logger := New(WithSink(sink))
const numGoroutines = 50
const messagesPerGoroutine = 1000
const samplingFactor = 100
const groupName = "stress-test"
var wg sync.WaitGroup
// Stress test with high concurrency
start := time.Now()
for g := 0; g < numGoroutines; g++ {
wg.Add(1)
go func(goroutineID int) {
defer wg.Done()
groupLogger := logger.SampleGroup(groupName, samplingFactor)
for i := 0; i < messagesPerGoroutine; i++ {
groupLogger.Info("Stress message {GoroutineID}-{Iteration}", goroutineID, i)
}
}(g)
}
wg.Wait()
duration := time.Since(start)
events := sink.Events()
totalMessages := numGoroutines * messagesPerGoroutine
expectedCount := totalMessages / samplingFactor
t.Logf("Processed %d messages in %v with %d goroutines", totalMessages, duration, numGoroutines)
t.Logf("Got %d sampled events (expected ~%d)", len(events), expectedCount)
// Ensure we got a reasonable number of events (within 20% tolerance for high concurrency)
tolerance := expectedCount / 5 // 20% tolerance
if len(events) < expectedCount-tolerance || len(events) > expectedCount+tolerance {
t.Errorf("Expected approximately %d events (±%d), got %d",
expectedCount, tolerance, len(events))
}
}
// TestGroupSamplingCacheMetrics tests the cache metrics functionality
func TestGroupSamplingCacheMetrics(t *testing.T) {
sink := sinks.NewMemorySink()
logger := New(WithSink(sink))
// Access group manager metrics (this requires accessing internals)
// We'll create multiple groups to test cache hits/misses
groups := []string{"group1", "group2", "group3", "group1", "group2"} // group1 and group2 accessed twice
for _, groupName := range groups {
groupLogger := logger.SampleGroup(groupName, 2)
groupLogger.Info("Test message for {Group}", groupName)
}
// Note: The cache metrics are internal to the SamplingGroupManager
// In a real scenario, you'd expose these metrics through the public API
// For now, this test verifies that the functionality works without error
events := sink.Events()
// Should have logged some messages (exact count depends on sampling)
if len(events) == 0 {
t.Error("Expected at least some events to be logged")
}
}
// TestSampleBackoffLargeFactors tests backoff behavior with large multiplication factors
func TestSampleBackoffLargeFactors(t *testing.T) {
testCases := []struct {
name string
factor float64
logs int
expectedMinLogs int
expectedMaxLogs int
}{
{"Small Factor", 2.0, 100, 7, 10}, // 1, 2, 4, 8, 16, 32, 64 = 7 logs
{"Medium Factor", 5.0, 100, 3, 5}, // 1, 5, 25 = 3 logs
{"Large Factor", 10.0, 1000, 4, 6}, // 1, 10, 100, 1000 = 4 logs
{"Very Large Factor", 100.0, 10000, 3, 4}, // 1, 100, 10000 = 3 logs
{"Invalid Factor", 0.5, 100, 7, 10}, // Should default to 2.0 due to validation
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
sink := sinks.NewMemorySink()
logger := New(WithSink(sink))
backoffLogger := logger.SampleBackoff("test-key-"+tc.name, tc.factor)
// Log the specified number of messages
for i := 1; i <= tc.logs; i++ {
backoffLogger.Error("Error {Count} with factor {Factor}", i, tc.factor)
}
events := sink.Events()
if len(events) < tc.expectedMinLogs || len(events) > tc.expectedMaxLogs {
t.Errorf("Factor %.1f with %d logs: expected %d-%d events, got %d",
tc.factor, tc.logs, tc.expectedMinLogs, tc.expectedMaxLogs, len(events))
}
// Verify the exponential pattern by checking that early messages were logged
if len(events) > 0 {
// First message should always be logged
if firstCount, ok := events[0].Properties["Count"].(int); ok {
if firstCount != 1 {
t.Errorf("Expected first logged message to be Count=1, got %d", firstCount)
}
}
}
})
}
}
// TestSampleBackoffKeyIsolation tests that different keys maintain separate backoff counters
func TestSampleBackoffKeyIsolation(t *testing.T) {
sink := sinks.NewMemorySink()
logger := New(WithSink(sink))
// Create backoff loggers with different keys but same factor
logger1 := logger.SampleBackoff("error-type-1", 2.0)
logger2 := logger.SampleBackoff("error-type-2", 2.0)
// Each should log their first message independently
logger1.Error("Error type 1 - attempt 1")
logger2.Error("Error type 2 - attempt 1")
logger1.Error("Error type 1 - attempt 2") // Should be logged (2nd for this key)
logger2.Error("Error type 2 - attempt 2") // Should be logged (2nd for this key)
logger1.Error("Error type 1 - attempt 3") // Should be skipped
logger2.Error("Error type 2 - attempt 3") // Should be skipped
logger1.Error("Error type 1 - attempt 4") // Should be logged (4th for this key)
logger2.Error("Error type 2 - attempt 4") // Should be logged (4th for this key)
events := sink.Events()
expectedCount := 6 // Messages 1,2,4 for each key
if len(events) != expectedCount {
t.Errorf("Expected %d events with isolated keys, got %d", expectedCount, len(events))
}
}
// TestLRUEvictionGroupSampling tests that LRU eviction works correctly in group sampling
func TestLRUEvictionGroupSampling(t *testing.T) {
sink := sinks.NewMemorySink()
// Create logger with limited capacity for testing eviction
// Note: We need to test this with the internal cache, which has default capacity
// For this test, we'll create many groups to potentially trigger eviction
logger := New(WithSink(sink))
const numGroups = 50 // Try to create more groups than might fit in cache
const messagesPerGroup = 5
// Create many different groups
for i := 0; i < numGroups; i++ {
groupName := fmt.Sprintf("group-%d", i)
groupLogger := logger.SampleGroup(groupName, 2) // Sample every 2nd message
for j := 1; j <= messagesPerGroup; j++ {
groupLogger.Info("Message {MessageNumber} for group {GroupName}", j, groupName)
}
}
// Verify that sampling still works correctly even with many groups
events := sink.Events()
// Each group should have sampled 3 out of 5 messages (1st, 3rd, 5th)
// So total should be approximately numGroups * 3
expectedMin := numGroups * 2 // Allow some tolerance
expectedMax := numGroups * 4
if len(events) < expectedMin || len(events) > expectedMax {
t.Errorf("Expected %d-%d events with %d groups, got %d",
expectedMin, expectedMax, numGroups, len(events))
}
// Verify we got messages from different groups
groupsFound := make(map[string]bool)
for _, event := range events {
if groupName, ok := event.Properties["GroupName"].(string); ok {
groupsFound[groupName] = true
}
}
// Should have messages from multiple groups
if len(groupsFound) < 10 {
t.Errorf("Expected messages from many groups, got from %d groups", len(groupsFound))
}
}
// TestLRUEvictionBackoffSampling tests LRU eviction with backoff sampling
func TestLRUEvictionBackoffSampling(t *testing.T) {
sink := sinks.NewMemorySink()
logger := New(WithSink(sink))
const numKeys = 100 // Create many backoff keys
const attemptsPerKey = 10
// Create many different backoff keys to test cache behavior
for i := 0; i < numKeys; i++ {
key := fmt.Sprintf("error-type-%d", i)
backoffLogger := logger.SampleBackoff(key, 2.0)
for j := 1; j <= attemptsPerKey; j++ {
backoffLogger.Error("Error {Attempt} for {ErrorType}", j, key)
}
}
events := sink.Events()
// With factor 2.0 and 10 attempts per key, each key should log approximately:
// Messages 1, 2, 4, 8 = 4 messages per key
expectedMin := numKeys * 3 // Allow some tolerance
expectedMax := numKeys * 5
if len(events) < expectedMin || len(events) > expectedMax {
t.Errorf("Expected %d-%d events with %d backoff keys, got %d",
expectedMin, expectedMax, numKeys, len(events))
}
// Verify we got messages for different error types
errorTypesFound := make(map[string]bool)
for _, event := range events {
if errorType, ok := event.Properties["ErrorType"].(string); ok {
errorTypesFound[errorType] = true
}
}
// Should have messages from multiple error types
if len(errorTypesFound) < 20 {
t.Errorf("Expected messages from many error types, got from %d types", len(errorTypesFound))
}
}
// TestMemoryUsageHighKeyCardinality tests memory behavior under high key cardinality
func TestMemoryUsageHighKeyCardinality(t *testing.T) {
sink := sinks.NewMemorySink()
logger := New(WithSink(sink))
// Test with many unique group names (high cardinality)
const numUniqueGroups = 1000
const messagesPerGroup = 2
initialEvents := len(sink.Events())
// Generate many unique group names with timestamp to ensure uniqueness
baseTime := time.Now().UnixNano()
for i := 0; i < numUniqueGroups; i++ {
groupName := fmt.Sprintf("unique-group-%d-%d", baseTime, i)
groupLogger := logger.SampleGroup(groupName, 1) // Log every message
for j := 0; j < messagesPerGroup; j++ {
groupLogger.Info("High cardinality test message {Index}", j)
}
}
events := sink.Events()
newEvents := len(events) - initialEvents
expectedEvents := numUniqueGroups * messagesPerGroup
if newEvents != expectedEvents {
t.Errorf("Expected %d events with high cardinality groups, got %d",
expectedEvents, newEvents)
}
// Test with many unique backoff keys
const numUniqueKeys = 500
baseTime2 := time.Now().UnixNano()
initialEvents2 := len(sink.Events())
for i := 0; i < numUniqueKeys; i++ {
key := fmt.Sprintf("unique-error-%d-%d", baseTime2, i)
backoffLogger := logger.SampleBackoff(key, 3.0)
// Log just enough to get the first message (which should always be logged)
backoffLogger.Error("High cardinality backoff test {KeyID}", i)
}
events2 := sink.Events()
newEvents2 := len(events2) - initialEvents2
expectedEvents2 := numUniqueKeys // Each key should log its first message
if newEvents2 != expectedEvents2 {
t.Errorf("Expected %d events with high cardinality backoff keys, got %d",
expectedEvents2, newEvents2)
}
t.Logf("Successfully handled %d unique groups and %d unique backoff keys",
numUniqueGroups, numUniqueKeys)
}
// TestSampleProfile tests the predefined sampling profiles
func TestSampleProfile(t *testing.T) {
testCases := []struct {
profileName string
shouldWork bool
}{
{"HighTrafficAPI", true},
{"BackgroundWorker", true},
{"DevelopmentDebug", true},
{"NonExistentProfile", false}, // Should return unchanged logger
}
for _, tc := range testCases {
t.Run(tc.profileName, func(t *testing.T) {
sink := sinks.NewMemorySink()
logger := New(WithSink(sink))
profileLogger := logger.SampleProfile(tc.profileName)
if tc.shouldWork {
// Should get a different logger instance (with sampling applied)
if profileLogger == logger {
t.Errorf("Expected different logger instance for profile %s", tc.profileName)
}
} else {
// Should get the same logger instance (unchanged)
if profileLogger != logger {
t.Errorf("Expected same logger instance for non-existent profile %s", tc.profileName)
}
}
// Try logging some messages
for i := 1; i <= 10; i++ {
profileLogger.Info("Test message {Number}", i)
}
events := sink.Events()
// For valid profiles, we expect some sampling (likely fewer than 10 events)
// For invalid profiles, no sampling should be applied (expect all 10 events)
if tc.shouldWork {
t.Logf("Profile %s: logged %d out of 10 events", tc.profileName, len(events))
} else {
if len(events) != 10 {
t.Errorf("Expected all 10 events for invalid profile, got %d", len(events))
}
}
})
}
}
// TestAdaptiveSampling tests the adaptive sampling functionality
func TestAdaptiveSampling(t *testing.T) {
sink := sinks.NewMemorySink()
logger := New(WithSink(sink))
// Create adaptive logger targeting 5 events per second
adaptiveLogger := logger.SampleAdaptive(5)
// Log a burst of messages
start := time.Now()
for i := 1; i <= 50; i++ {
adaptiveLogger.Info("Adaptive message {Number}", i)
time.Sleep(1 * time.Millisecond) // Small delay to spread over time
}
duration := time.Since(start)
events := sink.Events()
t.Logf("Adaptive sampling: logged %d out of 50 events in %v", len(events), duration)
// Should have sampled some messages (not necessarily exactly 5 due to adaptation)
if len(events) == 0 {
t.Error("Expected at least some events with adaptive sampling")
}
// Should not log all messages (unless rate adapted to 100%)
if len(events) == 50 {
t.Logf("Adaptive sampling logged all events (rate may have adapted to 100%%)")
}
}
// BenchmarkAdaptiveSamplingBasic benchmarks basic adaptive sampling performance
func BenchmarkAdaptiveSamplingBasic(b *testing.B) {
sink := sinks.NewMemorySink()
logger := New(WithSink(sink))
adaptiveLogger := logger.SampleAdaptive(1000) // Target 1000 events/sec
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
adaptiveLogger.Info("Benchmark message {Number}", i)
}
}
// BenchmarkAdaptiveSamplingConcurrent benchmarks concurrent adaptive sampling
func BenchmarkAdaptiveSamplingConcurrent(b *testing.B) {
sink := sinks.NewMemorySink()
logger := New(WithSink(sink))
adaptiveLogger := logger.SampleAdaptive(1000) // Target 1000 events/sec
b.ResetTimer()
b.ReportAllocs()
b.RunParallel(func(pb *testing.PB) {
i := 0
for pb.Next() {
adaptiveLogger.Info("Concurrent benchmark message {Number}", i)
i++
}
})
}
// BenchmarkAdaptiveSamplingHighFrequency benchmarks high-frequency adaptive sampling
func BenchmarkAdaptiveSamplingHighFrequency(b *testing.B) {
sink := sinks.NewMemorySink()
logger := New(WithSink(sink))
adaptiveLogger := logger.SampleAdaptive(10000) // Target 10,000 events/sec
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
adaptiveLogger.Info("High frequency message {Number}", i)
}
}
// BenchmarkAdaptiveSamplingWithOptions benchmarks adaptive sampling with custom options
func BenchmarkAdaptiveSamplingWithOptions(b *testing.B) {
sink := sinks.NewMemorySink()
logger := New(WithSink(sink))
adaptiveLogger := logger.SampleAdaptiveWithOptions(
1000, // Target 1000 events/sec
0.01, // Min rate 1%
1.0, // Max rate 100%
500*time.Millisecond, // Adjust every 500ms
)
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
adaptiveLogger.Info("Configured adaptive message {Number}", i)
}
}
// BenchmarkAdaptiveSamplingWithHysteresis benchmarks adaptive sampling with hysteresis and aggressiveness control
func BenchmarkAdaptiveSamplingWithHysteresis(b *testing.B) {
sink := sinks.NewMemorySink()
logger := New(WithSink(sink))
adaptiveLogger := logger.SampleAdaptiveWithHysteresis(
1000, // Target 1000 events/sec
0.001, // Min rate 0.1%
1.0, // Max rate 100%
500*time.Millisecond, // Adjust every 500ms
0.1, // Hysteresis threshold 10%
0.5, // Moderate aggressiveness
)
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
adaptiveLogger.Info("Hysteresis adaptive message {Number}", i)
}
}
// BenchmarkAdaptiveSamplingWithDampening benchmarks adaptive sampling with dampening for extreme load variations
func BenchmarkAdaptiveSamplingWithDampening(b *testing.B) {
sink := sinks.NewMemorySink()
logger := New(WithSink(sink))
adaptiveLogger := logger.SampleAdaptiveWithDampening(
1000, // Target 1000 events/sec
0.001, // Min rate 0.1%
1.0, // Max rate 100%
500*time.Millisecond, // Adjust every 500ms
0.15, // Hysteresis threshold 15%
0.7, // Moderate-high aggressiveness
0.4, // Moderate dampening
)
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
adaptiveLogger.Info("Dampening adaptive message {Number}", i)
}
}
// BenchmarkAdaptiveSamplingVsRegularSampling compares adaptive vs regular sampling
func BenchmarkAdaptiveSamplingVsRegularSampling(b *testing.B) {
sink := sinks.NewMemorySink()
logger := New(WithSink(sink))