package log import ( "fmt" "git.giftfish.de/ston1th/docstore/pkg/core" "strings" "sync" ) const defaultSize = 500 type ScanLog struct { // protects logs sync.RWMutex size int logs []string } func NewScanLog(size int) *ScanLog { if size <= 0 { size = defaultSize } return &ScanLog{size: size} } func (l *ScanLog) Printf(f string, v ...interface{}) { s := fmt.Sprintf(f, v...) Println(s) s = core.LogTime() + s l.Lock() llen := len(l.logs) if llen < l.size { l.logs = append(l.logs, s) } else if llen == l.size { l.logs = append(l.logs[1:], s) } l.Unlock() } func (l *ScanLog) Logs() (logs string) { l.RLock() logs = reverseJoin(l.logs, "\n") l.RUnlock() return } // reverseJoin is a reverse version of strings.Join // code taken from strings.Join func reverseJoin(a []string, sep string) string { switch len(a) { case 0: return "" case 1: return a[0] } n := len(sep) * (len(a) - 1) for i := 0; i < len(a); i++ { n += len(a[i]) } var b strings.Builder b.Grow(n) b.WriteString(a[len(a)-1]) for i := len(a) - 2; i >= 0; i-- { b.WriteString(sep) b.WriteString(a[i]) } return b.String() }