Tool to help you manage your Grafana dashboards using Git.

test.go 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. // Make a copy, for safety
  54. e := *t.Entries[i]
  55. return &e
  56. }
  57. // AllEntries returns all entries that were logged.
  58. func (t *Hook) AllEntries() []*logrus.Entry {
  59. t.mu.RLock()
  60. defer t.mu.RUnlock()
  61. // Make a copy so the returned value won't race with future log requests
  62. entries := make([]*logrus.Entry, len(t.Entries))
  63. for i, entry := range t.Entries {
  64. // Make a copy, for safety
  65. e := *entry
  66. entries[i] = &e
  67. }
  68. return entries
  69. }
  70. // Reset removes all Entries from this test hook.
  71. func (t *Hook) Reset() {
  72. t.mu.Lock()
  73. defer t.mu.Unlock()
  74. t.Entries = make([]*logrus.Entry, 0)
  75. }