github.com/pingcap/ticdc@v0.0.0-20220526033649-485a10ef2652/pkg/logutil/log_test.go (about) 1 // Copyright 2020 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 logutil 15 16 import ( 17 "context" 18 "path/filepath" 19 "testing" 20 21 "github.com/pingcap/check" 22 "github.com/pingcap/errors" 23 "github.com/pingcap/log" 24 "github.com/pingcap/ticdc/pkg/util/testleak" 25 "go.uber.org/zap" 26 "go.uber.org/zap/zapcore" 27 ) 28 29 func TestSuite(t *testing.T) { 30 check.TestingT(t) 31 } 32 33 type logSuite struct{} 34 35 var _ = check.Suite(&logSuite{}) 36 37 func (s *logSuite) TestInitLoggerAndSetLogLevel(c *check.C) { 38 defer testleak.AfterTest(c)() 39 f := filepath.Join(c.MkDir(), "test") 40 cfg := &Config{ 41 Level: "warning", 42 File: f, 43 } 44 cfg.Adjust() 45 err := InitLogger(cfg) 46 c.Assert(err, check.IsNil) 47 c.Assert(log.GetLevel(), check.Equals, zapcore.WarnLevel) 48 49 // Set a different level. 50 err = SetLogLevel("info") 51 c.Assert(err, check.IsNil) 52 c.Assert(log.GetLevel(), check.Equals, zapcore.InfoLevel) 53 54 // Set the same level. 55 err = SetLogLevel("info") 56 c.Assert(err, check.IsNil) 57 c.Assert(log.GetLevel(), check.Equals, zapcore.InfoLevel) 58 59 // Set an invalid level. 60 err = SetLogLevel("badlevel") 61 c.Assert(err, check.NotNil) 62 } 63 64 func (s *logSuite) TestZapErrorFilter(c *check.C) { 65 defer testleak.AfterTest(c)() 66 var ( 67 err = errors.New("test error") 68 testCases = []struct { 69 err error 70 filters []error 71 expected zap.Field 72 }{ 73 {nil, []error{}, zap.Error(nil)}, 74 {err, []error{}, zap.Error(err)}, 75 {err, []error{context.Canceled}, zap.Error(err)}, 76 {err, []error{err}, zap.Error(nil)}, 77 {context.Canceled, []error{context.Canceled}, zap.Error(nil)}, 78 {errors.Annotate(context.Canceled, "annotate error"), []error{context.Canceled}, zap.Error(nil)}, 79 } 80 ) 81 for _, tc := range testCases { 82 c.Assert(ZapErrorFilter(tc.err, tc.filters...), check.DeepEquals, tc.expected) 83 } 84 }