package logc import ( "basic.com/valib/bhomebus.git" "encoding/json" "fmt" uuid "github.com/satori/go.uuid" "time" ) const ( LevelFatal = iota + 1 LevelError LevelWarn LevelInfo LevelDebug ) const ( TypeManual = iota + 1 TypeLoginOut TypePollInfo TypeStackInfo TypeWarnInfo TypeRunInfo TypeSysInfo ) type LogInfo struct { ID string `gorm:"column:id;primary_key;unique" json:"id"` Timestamp string `gorm:"column:timestamp" json:"timestamp"` // 2020-12-03 14:39:41 ProcName string `gorm:"column:procName" json:"procName"` ProcID string `gorm:"column:procID" json:"procID"` Level int `gorm:"column:level" json:"level"` // 日志等级 Type int `gorm:"column:type" json:"type"` // 操作类型:人工操作,登录退出,轮循摄像机及对应算法,数据栈处理情况,异常情况等 UserID string `gorm:"column:userID" json:"userID"` // 用户id UserName string `gorm:"column:userName" json:"userName"` // 用户名字 Info string `gorm:"column:info" json:"info"` // 详情 } var ( msgChan chan []byte bhSock *bhomebus.Socket ProcName string ProcID string ) func Init(sock *bhomebus.Socket, procId string, procName string) { msgChan = make(chan []byte, 100) ProcName = procName ProcID = procId bhSock = sock go saveLoop() } func Save(level int, logType int,template string, v ...interface{}) { cache(level, logType, "", "", template, v) } func SaveManual(level int, logType int, userID string, userName string, template string, v ...interface{}) { cache(level, logType, userID, userName, template, v) } func cache(level int, logType int, userID string, userName string, template string, fmtArgs []interface{}) { // Format with Sprint, Sprintf, or neither. msg := template if msg == "" && len(fmtArgs) > 0 { msg = fmt.Sprint(fmtArgs...) } else if msg != "" && len(fmtArgs) > 0 { msg = fmt.Sprintf(template, fmtArgs...) } log := LogInfo { ID: uuid.NewV4().String(), Timestamp: time.Now().Format("2006-01-02 15:04:05"), ProcName: ProcName, ProcID: ProcID, Level: level, Type: logType, UserID: userID, UserName: userName, Info: msg, } data,err := json.Marshal(log) if err != nil { fmt.Println("json.Marshal(log) error:", log) return } msgChan <- data } const ( LogSaveTopic = "logSaveTopic" ) func saveLoop() { for { select { case data := <- msgChan: var nodes []bhomebus.NetNode nodes = append(nodes, bhomebus.NetNode{ Key: 8, }) bhSock.PubTimeout(nodes, LogSaveTopic, data, 1000) default: time.Sleep(10*time.Millisecond) } } }