123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- package log
- 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"`
- }
- func NewConn() LoggerInterface {
- conn := new(ConnWriter)
- conn.Level = TRACE
- return conn
- }
- func (cw *ConnWriter) Init(jsonconfig string) error {
- return json.Unmarshal([]byte(jsonconfig), cw)
- }
- func (cw *ConnWriter) WriteMsg(msg string, skip, level int) error {
- if cw.Level > level {
- return nil
- }
- if cw.neddedConnectOnMsg() {
- if err := cw.connect(); err != nil {
- return err
- }
- }
- if cw.ReconnectOnMsg {
- defer cw.innerWriter.Close()
- }
- cw.lg.Println(msg)
- return nil
- }
- func (_ *ConnWriter) Flush() {
- }
- func (cw *ConnWriter) Destroy() {
- if cw.innerWriter == nil {
- return
- }
- cw.innerWriter.Close()
- }
- func (cw *ConnWriter) connect() error {
- if cw.innerWriter != nil {
- cw.innerWriter.Close()
- cw.innerWriter = nil
- }
- conn, err := net.Dial(cw.Net, cw.Addr)
- if err != nil {
- return err
- }
- if tcpConn, ok := conn.(*net.TCPConn); ok {
- tcpConn.SetKeepAlive(true)
- }
- cw.innerWriter = conn
- cw.lg = log.New(conn, "", log.Ldate|log.Ltime)
- return nil
- }
- func (cw *ConnWriter) neddedConnectOnMsg() bool {
- if cw.Reconnect {
- cw.Reconnect = false
- return true
- }
- if cw.innerWriter == nil {
- return true
- }
- return cw.ReconnectOnMsg
- }
- func init() {
- Register("conn", NewConn)
- }
|