github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/engine/pkg/orm/log_test.go (about) 1 // Copyright 2022 PingCAP, 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 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package orm 15 16 import ( 17 "context" 18 "regexp" 19 "testing" 20 "time" 21 22 "github.com/pingcap/log" 23 "github.com/pingcap/tiflow/pkg/errors" 24 "github.com/stretchr/testify/require" 25 "go.uber.org/zap/zaptest" 26 "gorm.io/gorm" 27 ) 28 29 func TestLoggerOpt(t *testing.T) { 30 t.Parallel() 31 32 var op loggerOption 33 WithSlowThreshold(30 * time.Second)(&op) 34 require.Equal(t, 30*time.Second, op.slowThreshold) 35 36 require.False(t, op.ignoreTraceRecordNotFoundErr) 37 WithIgnoreTraceRecordNotFoundErr()(&op) 38 require.True(t, op.ignoreTraceRecordNotFoundErr) 39 } 40 41 func TestNewOrmLogger(t *testing.T) { 42 t.Parallel() 43 44 var buffer zaptest.Buffer 45 zapLg, _, err := log.InitLoggerWithWriteSyncer(&log.Config{Level: "warn"}, &buffer, nil) 46 require.NoError(t, err) 47 48 lg := NewOrmLogger(zapLg, WithSlowThreshold(3*time.Second), WithIgnoreTraceRecordNotFoundErr()) 49 lg.Info(context.TODO(), "%s test", "info") 50 require.Equal(t, 0, len(buffer.Lines())) 51 52 lg.Warn(context.TODO(), "%s test", "warn") 53 require.Regexp(t, regexp.QuoteMeta("warn test"), buffer.Stripped()) 54 buffer.Reset() 55 56 lg.Error(context.TODO(), "%s test", "error") 57 require.Regexp(t, regexp.QuoteMeta("error test"), buffer.Stripped()) 58 buffer.Reset() 59 60 fc := func() (sql string, rowsAffected int64) { return "sql test", 10 } 61 lg.Trace(context.TODO(), time.Now(), fc, nil) 62 require.Equal(t, 0, len(buffer.Lines())) 63 64 lg.Trace(context.TODO(), time.Now().Add(-10*time.Second), fc, errors.New("error test")) 65 require.Regexp(t, regexp.QuoteMeta("[ERROR]"), buffer.Stripped()) 66 require.Regexp(t, regexp.MustCompile(`\["slow log"\] \[elapsed=10.*s\] \[sql="sql test"\] \[affected-rows=10\] \[error="error test"\]`), buffer.Stripped()) 67 buffer.Reset() 68 69 lg.Trace(context.TODO(), time.Now(), fc, gorm.ErrRecordNotFound) 70 // expect no log here because it's a debug log 71 require.Equal(t, 0, len(buffer.Lines())) 72 buffer.Reset() 73 }