github.com/livekit/protocol@v1.16.1-0.20240517185851-47e4c6bba773/logger/zaputil/fieldsampler_test.go (about) 1 // Copyright 2023 LiveKit, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package zaputil 16 17 import ( 18 "fmt" 19 "math" 20 "testing" 21 22 "go.uber.org/zap" 23 "go.uber.org/zap/zapcore" 24 25 "github.com/stretchr/testify/require" 26 ) 27 28 func TestRoomSampleRate(t *testing.T) { 29 expectedRate := 0.50 30 n := 10000 31 32 c := &testCore{Core: zap.NewExample().Core()} 33 s := zap.New(NewFieldSampler(c, FieldSamplerConfig{ 34 FieldName: "field", 35 Rate: NewAtomicFieldSampleRate(expectedRate), 36 })).Sugar() 37 38 for i := 0; i < n; i++ { 39 s.Debugw("test", "field", fmt.Sprintf("field_%d", i)) 40 } 41 42 rate := float64(c.WriteCount()) / float64(n) 43 require.Greater(t, 0.01, math.Abs(rate-expectedRate)) 44 } 45 46 func TestRoomSamplerWith(t *testing.T) { 47 c := &testCore{Core: zap.NewExample().Core()} 48 s := zap.New(NewFieldSampler(c, FieldSamplerConfig{ 49 FieldName: "field", 50 Rate: NewAtomicFieldSampleRate(0), 51 }).(*fieldSampler)).Sugar() 52 53 s.Debugw("test", "field", "test") 54 require.Equal(t, 0, c.WriteCount()) 55 56 s.With("field", "test").Debugw("test") 57 require.Equal(t, 0, c.WriteCount()) 58 } 59 60 func TestRoomSampleFindSampleField(t *testing.T) { 61 s := NewFieldSampler(nil, FieldSamplerConfig{ 62 FieldName: "field", 63 Rate: NewAtomicFieldSampleRate(1), 64 }).(*fieldSampler) 65 66 v, ok := s.findSampleField([]zapcore.Field{zap.String("field", "test")}) 67 require.Equal(t, "test", v) 68 require.True(t, ok) 69 70 v, ok = s.findSampleField([]zapcore.Field{zap.Reflect("field", testStringLike("test"))}) 71 require.Equal(t, "test", v) 72 require.True(t, ok) 73 74 v, ok = s.findSampleField([]zapcore.Field{zap.Stringer("field", testStringer("test"))}) 75 require.Equal(t, "test", v) 76 require.True(t, ok) 77 78 _, ok = s.findSampleField([]zapcore.Field{zap.Int("field", 123)}) 79 require.False(t, ok) 80 81 _, ok = s.findSampleField([]zapcore.Field{}) 82 require.False(t, ok) 83 }