app/history/history.go

78 lines
1.0 KiB
Go
Raw Normal View History

2021-12-16 06:25:57 +00:00
package history
import (
"fmt"
"time"
2021-12-16 11:44:07 +00:00
"kumoly.io/kumoly/app/errors"
2021-12-16 06:25:57 +00:00
)
const (
ERROR = "ERROR"
INFO = "INFO"
)
type History struct {
ID uint `gorm:"primaryKey"`
CreatedAt time.Time
Module string
Type string
Message string
Body string
Issuer string
Caller string
Trace string
}
var Tunnel chan *History
var quit chan struct{}
2021-12-16 11:44:07 +00:00
var started chan struct{}
2021-12-16 06:25:57 +00:00
func init() {
Tunnel = make(chan *History)
2021-12-16 10:11:34 +00:00
quit = make(chan struct{}, 1)
2021-12-16 11:44:07 +00:00
started = make(chan struct{}, 1)
2021-12-16 06:25:57 +00:00
}
func Start(r Receiver) {
2021-12-16 11:44:07 +00:00
select {
case started <- struct{}{}:
default:
panic(errors.New(500, "history has already started!"))
}
2021-12-16 06:25:57 +00:00
go func() {
2021-12-16 10:11:34 +00:00
for {
select {
case h := <-Tunnel:
r(h)
case <-quit:
2021-12-16 11:44:07 +00:00
<-started
2021-12-16 10:11:34 +00:00
return
}
2021-12-16 06:25:57 +00:00
}
}()
}
func Stop() {
quit <- struct{}{}
}
2021-12-16 10:11:34 +00:00
func Send(h *History) {
2021-12-16 11:11:46 +00:00
if h.Type == "" {
h.Type = INFO
}
2021-12-16 10:11:34 +00:00
Tunnel <- h
}
2021-12-16 06:25:57 +00:00
type Receiver func(*History)
var DBReceiver Receiver = func(h *History) {
}
var ConsoleReceiver Receiver = func(h *History) {
fmt.Printf("%+v\n", h)
}