1
0
Fork 0
mirror of https://github.com/diamondburned/cchat-gtk.git synced 2024-10-31 19:44:23 +00:00
cchat-gtk/internal/log/log.go

83 lines
1.2 KiB
Go
Raw Normal View History

2020-05-26 06:51:06 +00:00
package log
import (
"context"
"errors"
2020-05-26 06:51:06 +00:00
"fmt"
2020-06-06 00:47:28 +00:00
"log"
2020-05-26 06:51:06 +00:00
"os"
"sync"
"time"
)
var globalBuffer struct {
sync.Mutex
entries []Entry
handlers []func(Entry)
}
func init() {
AddEntryHandler(func(entry Entry) {
fmt.Fprintln(os.Stderr, entry)
})
}
type Entry struct {
Time time.Time
Msg string
}
func (entry Entry) String() string {
return entry.Time.Format(time.Stamp) + ": " + entry.Msg
}
// AddEntryHandler adds a handler, which will run asynchronously.
func AddEntryHandler(fn func(Entry)) {
globalBuffer.handlers = append(globalBuffer.handlers, fn)
}
func Error(err error) {
// Ignore nil errors.
if err == nil {
return
}
// Ignore context cancel errors.
if errors.Is(err, context.Canceled) {
return
}
2020-05-26 06:51:06 +00:00
Write("Error: " + err.Error())
}
2020-06-04 23:00:41 +00:00
func Warn(err error) {
Write("Warn: " + err.Error())
}
2020-05-26 06:51:06 +00:00
func Write(msg string) {
WriteEntry(Entry{
Time: time.Now(),
Msg: msg,
})
}
func WriteEntry(entry Entry) {
go func() {
globalBuffer.Lock()
globalBuffer.entries = append(globalBuffer.entries, entry)
globalBuffer.Unlock()
for _, fn := range globalBuffer.handlers {
fn(entry)
}
}()
}
2020-06-06 00:47:28 +00:00
func Println(v ...interface{}) {
log.Println(v...)
}
2020-06-20 07:28:47 +00:00
func Printlnf(f string, v ...interface{}) {
log.Printf(f+"\n", v...)
}