logmania/log/hook/client/main.go

74 lines
1.4 KiB
Go
Raw Normal View History

2017-06-11 03:34:11 +02:00
package client
import (
"fmt"
"github.com/gorilla/websocket"
"github.com/genofire/logmania/log"
)
type Logger struct {
2017-06-12 22:32:27 +02:00
log.Logger
2017-06-11 03:34:11 +02:00
AboveLevel log.LogLevel
conn *websocket.Conn
2017-06-12 22:32:27 +02:00
closed bool
2017-06-11 03:34:11 +02:00
}
2017-06-12 22:32:27 +02:00
var CurrentLogger *Logger
func NewLogger(url, token string, AboveLevel log.LogLevel) *Logger {
c, _, err := websocket.DefaultDialer.Dial(fmt.Sprint(url, "/logger"), nil)
if err != nil {
log.Error("[logmania] error on connect: ", err)
return nil
}
err = c.WriteMessage(websocket.TextMessage, []byte(token))
if err != nil {
log.Error("[logmania] could not send token:", err)
return nil
}
return &Logger{
AboveLevel: AboveLevel,
conn: c,
}
}
func (l *Logger) Hook(e *log.Entry) {
if l.closed {
return
}
2017-06-11 03:34:11 +02:00
if e.Level < l.AboveLevel {
return
}
err := l.conn.WriteJSON(e)
if err != nil {
2017-06-12 22:32:27 +02:00
log.Error("[logmania] could not send log entry:", err)
l.Close()
}
}
func (l *Logger) Listen() {
for {
msgType, _, err := l.conn.ReadMessage()
if msgType == -1 {
l.closed = true
l.conn.Close()
return
}
if err != nil {
log.Warn("[logmania] close listener:", err)
}
2017-06-11 03:34:11 +02:00
}
}
func (l *Logger) Close() {
2017-06-12 22:32:27 +02:00
l.conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
l.closed = true
2017-06-11 03:34:11 +02:00
}
2017-06-12 22:32:27 +02:00
func Init(url, token string, AboveLevel log.LogLevel) *Logger {
CurrentLogger = NewLogger(url, token, AboveLevel)
go CurrentLogger.Listen()
log.AddLogger(CurrentLogger)
return CurrentLogger
2017-06-11 03:34:11 +02:00
}