diff options
author | Florian Klink <flokli@flokli.de> | 2019-12-02T11·03+0100 |
---|---|---|
committer | Florian Klink <flokli@flokli.de> | 2019-12-02T11·03+0100 |
commit | 118a88dace6e825e8cb713e644f5bcbcb753737b (patch) | |
tree | 688c462ac68c6464dd1a235eb383ca6aac2c88d7 /misc/rotatingloghandler.go | |
parent | 04a24a0c601c28d01e1110fb82f57c7a7c3f5d74 (diff) |
add rotatingloghandler which removes older log entries
Diffstat (limited to 'misc/rotatingloghandler.go')
-rw-r--r-- | misc/rotatingloghandler.go | 34 |
1 files changed, 34 insertions, 0 deletions
diff --git a/misc/rotatingloghandler.go b/misc/rotatingloghandler.go new file mode 100644 index 000000000000..3d4c5f3a837a --- /dev/null +++ b/misc/rotatingloghandler.go @@ -0,0 +1,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 +} |