示例#1
0
文件: net_log.go 项目: tengteng/logd
func (l *NetLog) logging(level int, msg string) {
	if level >= 0 && level < len(prefixes) {
		l.mutex.Lock()

		if l.conn == nil {
			l.conn, _ = getConnection(l.addr) //重连一次
		}

		if l.conn != nil {
			m := map[string]string{"time": time.Now().Format("2006/01/02 15:04:05"), "type": prefixes[level], "msg": msg, "ip": l.ip, "port": HeartBeatPort}
			data, err := json.Marshal(m)
			if err != nil {
				log.Println("marshal net log error:", err)
				return
			}
			data = tcp_pack.Pack(data)
			_, err = l.conn.Write(data)
			if err != nil {
				log.Println("send log failed: ", msg, "error:", err)
			} else {
				log.Println("send log :" + msg)
			}
		} else {
			log.Println("send log failed: ", msg, "error: no connection")
		}
		l.mutex.Unlock()
	}

}
示例#2
0
func (lr *LogReceiver) handleConnection(conn net.Conn) {
	defer conn.Close()
	for {
		var m map[string]string
		n, buf := tcp_pack.UnPack(conn)
		if n <= 0 {
			break
		}
		err := json.Unmarshal(buf, &m)
		if err == nil {
			_, ok := m["req"]
			if ok {
				m = lr.handleRegister(m)
				data, _ := json.Marshal(m)
				conn.Write(tcp_pack.Pack(data))
			} else {
				lr.handleLog(m)
			}
		}
	}
}
示例#3
0
//向monitor注册或取消注册,reg为true表示注册,否则是取消注册,返回true表示成功
func (this *HeartBeat) registerSelf(reg bool) bool {
	conn, err := lib.GetConnection(this.monitorAddr)
	if err != nil {
		return false
	}
	defer conn.Close()

	req := "register"
	if !reg {
		req = "unregister"
	}
	m := map[string]string{"req": req, "ip": lib.GetIp(), "port": this.port, "hostname": lib.GetHostname(), "role": this.role}
	msg, err := json.Marshal(m)
	if err != nil {
		loglib.Error("marshal " + req + " info error " + err.Error())
		return false
	}
	_, err = conn.Write(tcp_pack.Pack(msg))
	if err != nil {
		loglib.Error("send " + req + " info failed" + err.Error())
		return false
	} else {
		plen, ret := tcp_pack.UnPack(conn)

		if plen > 0 {
			err = json.Unmarshal(ret, &m)
			r, ok := m["err"]
			if err == nil && ok && r == "0" {
				loglib.Info(req + " to monitor success!")
				return true
			}
			loglib.Error(req + " heart beat failed!")
		}
	}
	return false
}