2020-05-26 06:51:06 +00:00
|
|
|
package log
|
|
|
|
|
|
|
|
import (
|
2020-06-13 07:29:32 +00:00
|
|
|
"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) {
|
2020-06-13 07:29:32 +00:00
|
|
|
// 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-07-09 07:19:18 +00:00
|
|
|
// Warn calls Info().
|
2020-06-04 23:00:41 +00:00
|
|
|
func Warn(err error) {
|
2020-07-09 07:19:18 +00:00
|
|
|
Info(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
func Info(err error) {
|
|
|
|
Write("Info: " + err.Error())
|
2020-06-04 23:00:41 +00:00
|
|
|
}
|
|
|
|
|
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...)
|
|
|
|
}
|