buflog.go 1009 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package buflog
  2. import (
  3. "bytes"
  4. "strings"
  5. "sync"
  6. )
  7. // BufLog implements a simple log buffer that can be supplied to a std
  8. // log instance. It stores logs up to N lines.
  9. type BufLog struct {
  10. maxLines int
  11. buf *bytes.Buffer
  12. lines []string
  13. sync.RWMutex
  14. }
  15. // New returns a new log buffer that stores up to maxLines lines.
  16. func New(maxLines int) *BufLog {
  17. return &BufLog{
  18. maxLines: maxLines,
  19. buf: &bytes.Buffer{},
  20. lines: make([]string, 0, maxLines),
  21. }
  22. }
  23. // Write writes a log item to the buffer maintaining maxLines capacity
  24. // using LIFO.
  25. func (bu *BufLog) Write(b []byte) (n int, err error) {
  26. bu.Lock()
  27. if len(bu.lines) >= bu.maxLines {
  28. bu.lines[0] = ""
  29. bu.lines = bu.lines[1:len(bu.lines)]
  30. }
  31. bu.lines = append(bu.lines, strings.TrimSpace(string(b)))
  32. bu.Unlock()
  33. return len(b), nil
  34. }
  35. // Lines returns the log lines.
  36. func (bu *BufLog) Lines() []string {
  37. bu.RLock()
  38. defer bu.RUnlock()
  39. out := make([]string, len(bu.lines))
  40. copy(out[:], bu.lines[:])
  41. return out
  42. }