1 /* 2 Copyright The containerd Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package logtest 18 19 import ( 20 "bytes" 21 "sync" 22 "testing" 23 24 "github.com/sirupsen/logrus" 25 ) 26 27 type testHook struct { 28 t testing.TB 29 fmt logrus.Formatter 30 mu sync.Mutex 31 } 32 33 func (*testHook) Levels() []logrus.Level { 34 return logrus.AllLevels 35 } 36 37 func (h *testHook) Fire(e *logrus.Entry) error { 38 s, err := h.fmt.Format(e) 39 if err != nil { 40 return err 41 } 42 43 // Because the logger could be called from multiple goroutines, 44 // but t.Log() is not designed for. 45 h.mu.Lock() 46 defer h.mu.Unlock() 47 h.t.Log(string(bytes.TrimRight(s, "\n"))) 48 49 return nil 50 } 51