logmania/log/hook/client/main.go

83 lines
1.8 KiB
Go
Raw Normal View History

2017-06-13 00:21:19 +02:00
// logger to bind at github.com/genofire/logmania/log.AddLogger to send log entries to logmania server
2017-06-11 03:34:11 +02:00
package client
import (
"fmt"
"github.com/gorilla/websocket"
"github.com/genofire/logmania/log"
)
2017-06-13 00:21:19 +02:00
// client logger
2017-06-11 03:34:11 +02:00
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-14 21:31:17 +02:00
const LOGGER_NAME = "client"
2017-06-13 00:21:19 +02:00
// CurrentLogger (for override settings e.g. AboveLevel)
2017-06-12 22:32:27 +02:00
var CurrentLogger *Logger
2017-06-13 00:21:19 +02:00
// create a new logmania client logger
2017-06-12 22:32:27 +02:00
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,
}
}
2017-06-13 00:21:19 +02:00
// handle a log entry (send to logmania server)
2017-06-12 22:32:27 +02:00
func (l *Logger) Hook(e *log.Entry) {
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
l.Close()
2017-06-24 13:05:01 +02:00
log.Error("[logmania] could not send log entry:", err)
2017-06-12 22:32:27 +02:00
}
}
2017-06-13 00:21:19 +02:00
// Listen if logmania server want to close the connection
2017-06-12 22:32:27 +02:00
func (l *Logger) Listen() {
for {
msgType, _, err := l.conn.ReadMessage()
if msgType == -1 {
l.conn.Close()
2017-06-14 21:31:17 +02:00
l.Close()
2017-06-12 22:32:27 +02:00
return
}
if err != nil {
2017-06-24 13:05:01 +02:00
l.Close()
2017-06-12 22:32:27 +02:00
log.Warn("[logmania] close listener:", err)
}
2017-06-11 03:34:11 +02:00
}
}
2017-06-13 00:21:19 +02:00
// close connection to logger
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, ""))
2017-06-14 21:31:17 +02:00
log.RemoveLogger(LOGGER_NAME)
2017-06-11 03:34:11 +02:00
}
2017-06-13 00:21:19 +02:00
// init logmania's client logger and bind
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()
2017-06-14 21:31:17 +02:00
log.AddLogger(LOGGER_NAME, CurrentLogger)
2017-06-12 22:32:27 +02:00
return CurrentLogger
2017-06-11 03:34:11 +02:00
}