github.com/astaxie/beego@v1.12.3/logs/conn.go (about) 1 // Copyright 2014 beego Author. All Rights Reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package logs 16 17 import ( 18 "encoding/json" 19 "io" 20 "net" 21 "time" 22 ) 23 24 // connWriter implements LoggerInterface. 25 // it writes messages in keep-live tcp connection. 26 type connWriter struct { 27 lg *logWriter 28 innerWriter io.WriteCloser 29 ReconnectOnMsg bool `json:"reconnectOnMsg"` 30 Reconnect bool `json:"reconnect"` 31 Net string `json:"net"` 32 Addr string `json:"addr"` 33 Level int `json:"level"` 34 } 35 36 // NewConn create new ConnWrite returning as LoggerInterface. 37 func NewConn() Logger { 38 conn := new(connWriter) 39 conn.Level = LevelTrace 40 return conn 41 } 42 43 // Init init connection writer with json config. 44 // json config only need key "level". 45 func (c *connWriter) Init(jsonConfig string) error { 46 return json.Unmarshal([]byte(jsonConfig), c) 47 } 48 49 // WriteMsg write message in connection. 50 // if connection is down, try to re-connect. 51 func (c *connWriter) WriteMsg(when time.Time, msg string, level int) error { 52 if level > c.Level { 53 return nil 54 } 55 if c.needToConnectOnMsg() { 56 err := c.connect() 57 if err != nil { 58 return err 59 } 60 } 61 62 if c.ReconnectOnMsg { 63 defer c.innerWriter.Close() 64 } 65 66 _, err := c.lg.writeln(when, msg) 67 if err != nil { 68 return err 69 } 70 return nil 71 } 72 73 // Flush implementing method. empty. 74 func (c *connWriter) Flush() { 75 76 } 77 78 // Destroy destroy connection writer and close tcp listener. 79 func (c *connWriter) Destroy() { 80 if c.innerWriter != nil { 81 c.innerWriter.Close() 82 } 83 } 84 85 func (c *connWriter) connect() error { 86 if c.innerWriter != nil { 87 c.innerWriter.Close() 88 c.innerWriter = nil 89 } 90 91 conn, err := net.Dial(c.Net, c.Addr) 92 if err != nil { 93 return err 94 } 95 96 if tcpConn, ok := conn.(*net.TCPConn); ok { 97 tcpConn.SetKeepAlive(true) 98 } 99 100 c.innerWriter = conn 101 c.lg = newLogWriter(conn) 102 return nil 103 } 104 105 func (c *connWriter) needToConnectOnMsg() bool { 106 if c.Reconnect { 107 return true 108 } 109 110 if c.innerWriter == nil { 111 return true 112 } 113 114 return c.ReconnectOnMsg 115 } 116 117 func init() { 118 Register(AdapterConn, NewConn) 119 }