about summary refs log tree commit diff
path: root/misc/rotatingloghandler.go
blob: 3d4c5f3a837ab0a19b671c2b1699ce58186b0b74 (plain) (blame)
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
package misc

import (
	"sync"

	"github.com/apex/log"
)

// RotatingLogHandler implementation.
type RotatingLogHandler struct {
	mu         sync.Mutex
	Entries    []*log.Entry
	maxEntries int
}

// NewRotatingLogHandler creates a new rotating log handler
func NewRotatingLogHandler(maxEntries int) *RotatingLogHandler {
	return &RotatingLogHandler{
		maxEntries: maxEntries,
	}
}

// HandleLog implements log.Handler.
func (h *RotatingLogHandler) HandleLog(e *log.Entry) error {
	h.mu.Lock()
	defer h.mu.Unlock()
	// drop tail if we have more entries than maxEntries
	if len(h.Entries) > h.maxEntries {
		h.Entries = append([]*log.Entry{e}, h.Entries[:(h.maxEntries-2)]...)
	} else {
		h.Entries = append([]*log.Entry{e}, h.Entries...)
	}
	return nil
}