Fix: make log api unblocked

This commit is contained in:
Dreamacro 2022-04-25 23:22:58 +08:00
parent 6a92c6af4e
commit aef4dd3fe7
2 changed files with 19 additions and 7 deletions

View file

@ -208,16 +208,27 @@ func getLogs(w http.ResponseWriter, r *http.Request) {
render.Status(r, http.StatusOK)
}
ch := make(chan log.Event, 1024)
sub := log.Subscribe()
defer log.UnSubscribe(sub)
buf := &bytes.Buffer{}
var err error
go func() {
for elm := range sub {
buf.Reset()
log := elm.(*log.Event)
log := elm.(log.Event)
select {
case ch <- log:
default:
}
}
close(ch)
}()
for log := range ch {
if log.LogLevel < level {
continue
}
buf.Reset()
if err := json.NewEncoder(buf).Encode(Log{
Type: log.Type(),
@ -226,6 +237,7 @@ func getLogs(w http.ResponseWriter, r *http.Request) {
break
}
var err error
if wsConn == nil {
_, err = w.Write(buf.Bytes())
w.(http.Flusher).Flush()

View file

@ -74,7 +74,7 @@ func SetLevel(newLevel LogLevel) {
level = newLevel
}
func print(data *Event) {
func print(data Event) {
if data.LogLevel < level {
return
}
@ -91,8 +91,8 @@ func print(data *Event) {
}
}
func newLog(logLevel LogLevel, format string, v ...any) *Event {
return &Event{
func newLog(logLevel LogLevel, format string, v ...any) Event {
return Event{
LogLevel: logLevel,
Payload: fmt.Sprintf(format, v...),
}