1
0
mirror of https://github.com/astaxie/beego.git synced 2024-12-24 00:10:48 +00:00
Beego/logs/conn.go

114 lines
2.2 KiB
Go
Raw Normal View History

2014-04-12 05:18:18 +00:00
// Beego (http://beego.me/)
// @description beego is an open-source, high-performance web framework for the Go programming language.
// @link http://github.com/astaxie/beego for the canonical source repository
// @license http://github.com/astaxie/beego/blob/master/LICENSE
// @authors astaxie
2013-08-27 15:48:58 +00:00
package logs
import (
"encoding/json"
"io"
"log"
"net"
)
2013-12-30 15:32:57 +00:00
// ConnWriter implements LoggerInterface.
// it writes messages in keep-live tcp connection.
2013-08-27 15:48:58 +00:00
type ConnWriter struct {
lg *log.Logger
innerWriter io.WriteCloser
ReconnectOnMsg bool `json:"reconnectOnMsg"`
Reconnect bool `json:"reconnect"`
Net string `json:"net"`
Addr string `json:"addr"`
Level int `json:"level"`
2013-08-27 15:48:58 +00:00
}
2013-12-30 15:32:57 +00:00
// create new ConnWrite returning as LoggerInterface.
2013-08-27 15:48:58 +00:00
func NewConn() LoggerInterface {
conn := new(ConnWriter)
conn.Level = LevelTrace
2013-08-27 15:48:58 +00:00
return conn
}
2013-12-30 15:32:57 +00:00
// init connection writer with json config.
// json config only need key "level".
2013-08-27 15:48:58 +00:00
func (c *ConnWriter) Init(jsonconfig string) error {
err := json.Unmarshal([]byte(jsonconfig), c)
2013-08-27 15:48:58 +00:00
if err != nil {
return err
}
return nil
}
2013-12-30 15:32:57 +00:00
// write message in connection.
// if connection is down, try to re-connect.
2013-08-27 15:48:58 +00:00
func (c *ConnWriter) WriteMsg(msg string, level int) error {
if level < c.Level {
2013-08-27 15:48:58 +00:00
return nil
}
if c.neddedConnectOnMsg() {
err := c.connect()
if err != nil {
return err
}
}
if c.ReconnectOnMsg {
2013-08-27 15:48:58 +00:00
defer c.innerWriter.Close()
}
c.lg.Println(msg)
return nil
}
2013-12-30 15:32:57 +00:00
// implementing method. empty.
2013-11-27 09:50:10 +00:00
func (c *ConnWriter) Flush() {
}
2013-12-30 15:32:57 +00:00
// destroy connection writer and close tcp listener.
2013-08-27 15:48:58 +00:00
func (c *ConnWriter) Destroy() {
if c.innerWriter == nil {
return
}
c.innerWriter.Close()
}
func (c *ConnWriter) connect() error {
if c.innerWriter != nil {
c.innerWriter.Close()
c.innerWriter = nil
}
conn, err := net.Dial(c.Net, c.Addr)
2013-08-27 15:48:58 +00:00
if err != nil {
return err
}
2013-12-07 05:26:22 +00:00
if tcpConn, ok := conn.(*net.TCPConn); ok {
2013-08-27 15:48:58 +00:00
tcpConn.SetKeepAlive(true)
}
c.innerWriter = conn
c.lg = log.New(conn, "", log.Ldate|log.Ltime)
return nil
}
func (c *ConnWriter) neddedConnectOnMsg() bool {
if c.Reconnect {
c.Reconnect = false
2013-08-27 15:48:58 +00:00
return true
}
if c.innerWriter == nil {
return true
}
return c.ReconnectOnMsg
2013-08-27 15:48:58 +00:00
}
func init() {
Register("conn", NewConn)
}