Refactor how logs are handled.

This commit is contained in:
2022-04-04 19:10:07 +09:30
parent fbd267e687
commit ba7ae21248
9 changed files with 171 additions and 104 deletions

View File

@@ -1,10 +1,14 @@
package log
import (
"log"
"fmt"
"time"
)
type Logger interface {
WriteEntry(l LogEntry)
}
type LogEntryType string
type LogEntry struct {
@@ -19,28 +23,73 @@ const (
LogTypeDebug = "debug"
)
var LogEntries []LogEntry
var loggers []Logger
var logInput chan LogEntry
var Memory *MemoryLogger
func init() {
// create some loggers
Memory = &MemoryLogger{maxsize: 100}
stdout := &StdoutLogger{}
loggers = []Logger{Memory, stdout}
// wait for log entries
logInput = make(chan LogEntry)
go func() {
for {
aLog := <-logInput
LogEntries = append(LogEntries, aLog)
for len(LogEntries) > 100 {
LogEntries = LogEntries[1:]
for _, l := range loggers {
l.WriteEntry(aLog)
}
}
}()
}
func SendLog(entry string, entryType LogEntryType) {
func Debug(entry string) {
logInput <- LogEntry{
Timestamp: time.Now(),
Entry: entry,
Type: entryType,
Type: LogTypeDebug,
}
}
func Debugf(entry string, args ...interface{}) {
logInput <- LogEntry{
Timestamp: time.Now(),
Entry: fmt.Sprintf(entry, args...),
Type: LogTypeDebug,
}
}
func Info(entry string) {
logInput <- LogEntry{
Timestamp: time.Now(),
Entry: entry,
Type: LogTypeInfo,
}
}
func Infof(entry string, args ...interface{}) {
logInput <- LogEntry{
Timestamp: time.Now(),
Entry: fmt.Sprintf(entry, args...),
Type: LogTypeInfo,
}
}
func Error(entry string) {
logInput <- LogEntry{
Timestamp: time.Now(),
Entry: entry,
Type: LogTypeError,
}
}
func Errorf(entry string, args ...interface{}) {
logInput <- LogEntry{
Timestamp: time.Now(),
Entry: fmt.Sprintf(entry, args...),
Type: LogTypeError,
}
log.Printf("%6s: %s", entryType, entry)
}

29
log/memory.go Normal file
View File

@@ -0,0 +1,29 @@
package log
import (
"sync"
)
type MemoryLogger struct {
size int
entries []LogEntry
maxsize int
lock sync.Mutex
}
func (m *MemoryLogger) WriteEntry(l LogEntry) {
// xxx needs mutex
// if m.entries == nil {
// m.entries = make([]LogEntry, 0)
// }
m.lock.Lock()
m.entries = append(m.entries, l)
if len(m.entries) > m.maxsize {
m.entries = m.entries[1:]
}
m.lock.Unlock()
}
func (m *MemoryLogger) Entries() []LogEntry {
return m.entries
}

12
log/stdout.go Normal file
View File

@@ -0,0 +1,12 @@
package log
import (
"log"
)
type StdoutLogger struct {
}
func (m StdoutLogger) WriteEntry(l LogEntry) {
log.Printf("%-6s %s", l.Type, l.Entry)
}