docstore/pkg/log/scanlog.go
2021-11-05 22:10:52 +01:00

72 lines
1.2 KiB
Go

// Copyright (C) 2021 Marius Schellenberger
package log
import (
"fmt"
"git.giftfish.de/ston1th/docstore/pkg/core"
"strings"
"sync"
)
const defaultSize = 500
type ScanLog struct {
// protects logs
mu 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.mu.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.mu.Unlock()
}
func (l *ScanLog) Logs() (logs string) {
l.mu.RLock()
logs = reverseJoin(l.logs, "\n")
l.mu.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()
}