File: inmemory.go

package info (click to toggle)
golang-github-crc-org-crc 2.34.0%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,548 kB
  • sloc: sh: 398; makefile: 326; javascript: 40
file content (44 lines) | stat: -rw-r--r-- 862 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package logging

import (
	"container/ring"
	"sync"

	"github.com/sirupsen/logrus"
)

// This hook keeps in memory n messages from error to info level
type inMemoryHook struct {
	messages *ring.Ring
	lock     sync.RWMutex
}

func newInMemoryHook(size int) *inMemoryHook {
	return &inMemoryHook{
		messages: ring.New(size),
	}
}

func (h *inMemoryHook) Levels() []logrus.Level {
	return []logrus.Level{logrus.InfoLevel, logrus.WarnLevel, logrus.ErrorLevel}
}

func (h *inMemoryHook) Fire(entry *logrus.Entry) error {
	h.lock.Lock()
	defer h.lock.Unlock()
	h.messages.Value = entry.Message
	h.messages = h.messages.Next()
	return nil
}

func (h *inMemoryHook) Messages() []string {
	h.lock.RLock()
	defer h.lock.RUnlock()
	var ret []string
	h.messages.Do(func(elem interface{}) {
		if str, ok := elem.(string); ok {
			ret = append(ret, str)
		}
	})
	return ret
}