test.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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.
  4. package test
  5. import (
  6. "io/ioutil"
  7. "sync"
  8. "github.com/sirupsen/logrus"
  9. )
  10. // Hook is a hook designed for dealing with logs in test scenarios.
  11. type Hook struct {
  12. // Entries is an array of all entries that have been received by this hook.
  13. // For safe access, use the AllEntries() method, rather than reading this
  14. // value directly.
  15. Entries []logrus.Entry
  16. mu sync.RWMutex
  17. }
  18. // NewGlobal installs a test hook for the global logger.
  19. func NewGlobal() *Hook {
  20. hook := new(Hook)
  21. logrus.AddHook(hook)
  22. return hook
  23. }
  24. // NewLocal installs a test hook for a given local logger.
  25. func NewLocal(logger *logrus.Logger) *Hook {
  26. hook := new(Hook)
  27. logger.Hooks.Add(hook)
  28. return hook
  29. }
  30. // NewNullLogger creates a discarding logger and installs the test hook.
  31. func NewNullLogger() (*logrus.Logger, *Hook) {
  32. logger := logrus.New()
  33. logger.Out = ioutil.Discard
  34. return logger, NewLocal(logger)
  35. }
  36. func (t *Hook) Fire(e *logrus.Entry) error {
  37. t.mu.Lock()
  38. defer t.mu.Unlock()
  39. t.Entries = append(t.Entries, *e)
  40. return nil
  41. }
  42. func (t *Hook) Levels() []logrus.Level {
  43. return logrus.AllLevels
  44. }
  45. // LastEntry returns the last entry that was logged or nil.
  46. func (t *Hook) LastEntry() *logrus.Entry {
  47. t.mu.RLock()
  48. defer t.mu.RUnlock()
  49. i := len(t.Entries) - 1
  50. if i < 0 {
  51. return nil
  52. }
  53. return &t.Entries[i]
  54. }
  55. // AllEntries returns all entries that were logged.
  56. func (t *Hook) AllEntries() []*logrus.Entry {
  57. t.mu.RLock()
  58. defer t.mu.RUnlock()
  59. // Make a copy so the returned value won't race with future log requests
  60. entries := make([]*logrus.Entry, len(t.Entries))
  61. for i := 0; i < len(t.Entries); i++ {
  62. // Make a copy, for safety
  63. entries[i] = &t.Entries[i]
  64. }
  65. return entries
  66. }
  67. // Reset removes all Entries from this test hook.
  68. func (t *Hook) Reset() {
  69. t.mu.Lock()
  70. defer t.mu.Unlock()
  71. t.Entries = make([]logrus.Entry, 0)
  72. }