1 // The Test package is used for testing logrus. It is here for backwards
2 // compatibility from when logrus' organization was upper-case. Please use
3 // lower-case logrus and the `null` package instead of this one.
10 "github.com/sirupsen/logrus"
13 // Hook is a hook designed for dealing with logs in test scenarios.
15 // Entries is an array of all entries that have been received by this hook.
16 // For safe access, use the AllEntries() method, rather than reading this
18 Entries []*logrus.Entry
22 // NewGlobal installs a test hook for the global logger.
23 func NewGlobal() *Hook {
32 // NewLocal installs a test hook for a given local logger.
33 func NewLocal(logger *logrus.Logger) *Hook {
36 logger.Hooks.Add(hook)
42 // NewNullLogger creates a discarding logger and installs the test hook.
43 func NewNullLogger() (*logrus.Logger, *Hook) {
45 logger := logrus.New()
46 logger.Out = ioutil.Discard
48 return logger, NewLocal(logger)
52 func (t *Hook) Fire(e *logrus.Entry) error {
55 t.Entries = append(t.Entries, e)
59 func (t *Hook) Levels() []logrus.Level {
60 return logrus.AllLevels
63 // LastEntry returns the last entry that was logged or nil.
64 func (t *Hook) LastEntry() *logrus.Entry {
67 i := len(t.Entries) - 1
71 // Make a copy, for safety
76 // AllEntries returns all entries that were logged.
77 func (t *Hook) AllEntries() []*logrus.Entry {
80 // Make a copy so the returned value won't race with future log requests
81 entries := make([]*logrus.Entry, len(t.Entries))
82 for i, entry := range t.Entries {
83 // Make a copy, for safety
90 // Reset removes all Entries from this test hook.
91 func (t *Hook) Reset() {
94 t.Entries = make([]*logrus.Entry, 0)