2015-05-13 15:14:34 +03:00
|
|
|
package test
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io/ioutil"
|
|
|
|
|
2016-12-02 02:53:16 +03:00
|
|
|
"github.com/Sirupsen/logrus"
|
2015-05-13 15:14:34 +03:00
|
|
|
)
|
|
|
|
|
2017-04-20 10:29:15 +03:00
|
|
|
// Hook is a hook designed for dealing with logs in test scenarios.
|
2015-05-13 15:14:34 +03:00
|
|
|
type Hook struct {
|
|
|
|
Entries []*logrus.Entry
|
|
|
|
}
|
|
|
|
|
2017-04-20 10:29:15 +03:00
|
|
|
// NewGlobal installs a test hook for the global logger.
|
2015-05-13 15:14:34 +03:00
|
|
|
func NewGlobal() *Hook {
|
|
|
|
|
|
|
|
hook := new(Hook)
|
|
|
|
logrus.AddHook(hook)
|
|
|
|
|
|
|
|
return hook
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2017-04-20 10:29:15 +03:00
|
|
|
// NewLocal installs a test hook for a given local logger.
|
2015-05-13 15:14:34 +03:00
|
|
|
func NewLocal(logger *logrus.Logger) *Hook {
|
|
|
|
|
|
|
|
hook := new(Hook)
|
|
|
|
logger.Hooks.Add(hook)
|
|
|
|
|
|
|
|
return hook
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2017-04-20 10:29:15 +03:00
|
|
|
// NewNullLogger creates a discarding logger and installs the test hook.
|
2015-05-13 15:14:34 +03:00
|
|
|
func NewNullLogger() (*logrus.Logger, *Hook) {
|
|
|
|
|
|
|
|
logger := logrus.New()
|
|
|
|
logger.Out = ioutil.Discard
|
|
|
|
|
|
|
|
return logger, NewLocal(logger)
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *Hook) Fire(e *logrus.Entry) error {
|
|
|
|
t.Entries = append(t.Entries, e)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *Hook) Levels() []logrus.Level {
|
|
|
|
return logrus.AllLevels
|
|
|
|
}
|
|
|
|
|
|
|
|
// LastEntry returns the last entry that was logged or nil.
|
|
|
|
func (t *Hook) LastEntry() (l *logrus.Entry) {
|
|
|
|
|
|
|
|
if i := len(t.Entries) - 1; i < 0 {
|
|
|
|
return nil
|
|
|
|
} else {
|
|
|
|
return t.Entries[i]
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
// Reset removes all Entries from this test hook.
|
|
|
|
func (t *Hook) Reset() {
|
|
|
|
t.Entries = make([]*logrus.Entry, 0)
|
|
|
|
}
|