github.com/secure-build/gitlab-runner@v12.5.0+incompatible/log/test/hook.go (about)

     1  package test
     2  
     3  import (
     4  	"github.com/sirupsen/logrus"
     5  	"github.com/sirupsen/logrus/hooks/test"
     6  )
     7  
     8  // NewHook will create a new global hook that can be used for tests after which
     9  // it will remove when the returned function invoked.
    10  //
    11  // This shouldn't be used when you are writing a new package/structure, you
    12  // should instead pass the logger to that struct and add the Hook to that struct
    13  // only, try to avoid the global logger. This has multiple benefits, for example
    14  // having that struct with specific logger settings that doesn't effect the
    15  // logger in another part of the application. For example:
    16  //
    17  // type MyNewStruct struct {
    18  // 		logger   logrus.FieldLogger
    19  // }
    20  //
    21  // The more hooks we add to the tests the more memory we are leaking.
    22  func NewHook() (*test.Hook, func()) {
    23  	// Copy all the previous hooks so we revert back to that state.
    24  	oldHooks := logrus.LevelHooks{}
    25  	for level, hooks := range logrus.StandardLogger().Hooks {
    26  		oldHooks[level] = hooks
    27  	}
    28  
    29  	newHook := test.NewGlobal()
    30  	return newHook, func() {
    31  		logrus.StandardLogger().ReplaceHooks(oldHooks)
    32  	}
    33  }