1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-16 01:50:54 +00:00
Beego/logs/conn.go

99 lines
1.5 KiB
Go
Raw Normal View History

2013-08-27 15:48:58 +00:00
package logs
import (
"encoding/json"
"io"
"log"
"net"
)
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
}
func NewConn() LoggerInterface {
conn := new(ConnWriter)
conn.Level = LevelTrace
2013-08-27 15:48:58 +00:00
return conn
}
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
}
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-11-27 09:50:10 +00:00
func (c *ConnWriter) Flush() {
}
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)
}