github.com/hedzr/evendeep@v0.4.8/dbglog/logex_copy.go (about)

     1  package dbglog
     2  
     3  // a little copy from logex, so we can avoid importing it
     4  
     5  import (
     6  	"io"
     7  	"testing"
     8  
     9  	"github.com/hedzr/log"
    10  )
    11  
    12  // LogCapturer reroutes testing.T log output
    13  type LogCapturer interface {
    14  	Release()
    15  }
    16  
    17  type logCapturer struct {
    18  	testing.TB
    19  	origOut io.Writer
    20  }
    21  
    22  func (tl logCapturer) Write(p []byte) (n int, err error) {
    23  	tl.TB.Logf(string(p))
    24  	return len(p), nil
    25  }
    26  
    27  func (tl logCapturer) Release() {
    28  	log.SetOutput(tl.origOut)
    29  }
    30  
    31  // NewCaptureLog redirects logrus output to testing.Log
    32  func NewCaptureLog(tb testing.TB) LogCapturer {
    33  	lc := logCapturer{TB: tb, origOut: log.GetOutput()}
    34  	if !testing.Verbose() {
    35  		log.SetOutput(lc)
    36  	}
    37  	return &lc
    38  }
    39  
    40  // // NewCaptureLogOld redirects logrus output to testing.Log
    41  // func NewCaptureLogOld(tb testing.TB) LogCapturer {
    42  // 	lc := logCapturer{TB: tb, origOut: logrus.StandardLogger().Out}
    43  // 	if !testing.Verbose() {
    44  // 		log.SetOutput(lc)
    45  // 	}
    46  // 	return &lc
    47  // }
    48  
    49  // CaptureLog redirects logrus output to testing.Log
    50  func CaptureLog(tb testing.TB) LogCapturer {
    51  	lc := logCapturer{TB: tb, origOut: log.GetOutput()}
    52  	log.SetOutput(lc)
    53  	return &lc
    54  }