package pkg
import (
"time"
)
const caches = 1000
type log struct {
limitNum int
limitTime time.Duration
ch chan string
}
func NewLog(limitNum int, limitTime time.Duration) *log {
return &log{
limitNum: limitNum,
limitTime: limitTime,
ch: make(chan string, caches),
}
}
func (l *log) Pub(log string) {
l.ch <- log
}
func (l *log) Sub(saveFunc func([]string)) {
timer := time.NewTimer(l.limitTime)
rows := make([]string, 0, l.limitNum)
for {
select {
case <-timer.C:
saveFunc(rows)
rows = l.reset(rows, timer)
case log, ok := <-l.ch:
if log != "" {
rows = append(rows, log)
}
if len(rows) == l.limitNum {
saveFunc(rows)
rows = l.reset(rows, timer)
}
if !ok && len(rows) == 0 {
return
}
}
}
}
func (l *log) Close() {
close(l.ch)
}
func (l *log) reset(rows []string, timer *time.Timer) []string {
rows = make([]string, 0, l.limitNum)
timer.Stop()
timer.Reset(l.limitTime)
return rows
}