From d329992729098670124003a8f8558c9447981e7c Mon Sep 17 00:00:00 2001
From: zhangzengfei <zhangzengfei@smartai.com>
Date: 星期一, 24 一月 2022 11:41:39 +0800
Subject: [PATCH] 系统日志添加创建时间

---
 logc.go |  237 +++++++++++++++++++++++++++++++++++++----------------------
 1 files changed, 149 insertions(+), 88 deletions(-)

diff --git a/logc.go b/logc.go
index 79462d9..515dfc2 100644
--- a/logc.go
+++ b/logc.go
@@ -1,11 +1,9 @@
 package logc
 
 import (
-	"basic.com/valib/bhomebus.git"
-
-	"encoding/json"
+	"basic.com/valib/c_bhomebus.git/proto/source/bhome_msg"
 	"fmt"
-	uuid "github.com/satori/go.uuid"
+	"sync"
 	"time"
 )
 
@@ -18,14 +16,19 @@
 )
 
 const (
-	TypeManual = iota + 1  //浜哄伐鎿嶄綔鏃ュ織,绯荤粺鍗囩骇,鎽勫儚鏈轰慨鏀�,绠楁硶淇敼...
-	TypeLoginOut //鐧诲綍鐧诲嚭鏃ュ織
-	TypePollInfo //杞贰鎽勫儚鏈哄強鍏跺搴旂殑绠楁硶
-	TypeStackInfo //鏁版嵁鏍堝鐞嗘儏鍐�
-	TypeWarnInfo //鏁呴殰淇℃伅
-	TypeRunInfo //杩愯鎯呭喌,gpu,mem,cpu
-	TypeSysInfo //绯荤粺鍙傛暟鍙樻洿,ip,server name,寮�鍏虫満淇℃伅
+	TypeManual    = iota + 1 //浜哄伐鎿嶄綔鏃ュ織,绯荤粺鍗囩骇,鎽勫儚鏈轰慨鏀�,绠楁硶淇敼...
+	TypeLoginOut             //鐧诲綍鐧诲嚭鏃ュ織
+	TypePollInfo             //杞贰鎽勫儚鏈哄強鍏跺搴旂殑绠楁硶
+	TypeStackInfo            //鏁版嵁鏍堝鐞嗘儏鍐�
+	TypeWarnInfo             //鏁呴殰淇℃伅
+	TypeRunInfo              //杩愯鎯呭喌,gpu,mem,cpu
+	TypeSysInfo              //绯荤粺鍙傛暟鍙樻洿,ip,server name,寮�鍏虫満淇℃伅
 )
+
+type LogPrinter interface {
+	Marshal() ([]byte, error)
+	Topic() string
+}
 
 type LogInfo struct {
 	ID        string `gorm:"column:id;primary_key;unique" json:"id"`
@@ -39,102 +42,160 @@
 	Info      string `gorm:"column:info" json:"info"`         // 璇︽儏
 }
 
+type LogRegister struct {
+	Nodes   []bhome_msg.BHAddress
+	Topic   string
+	Payload []byte
+}
+
+type LogReportCallback func(*LogRegister)
+
 var (
-	msgChan chan []byte
-	bhSock *bhomebus.Socket
-	pubFn func(nodes []bhomebus.NetNode, topic string, data []byte, milliseconds int) int
+	logCh    chan LogPrinter
+	logger   *Log
 	ProcName string
-	ProcID string
+	ProcID   string
 )
 
-func InitBySock(sock *bhomebus.Socket, procId string, procName string) bool {
-	msgChan = make(chan []byte, 100)
-	ProcName = procName
-	ProcID = procId
-	bhSock = sock
-	if bhSock == nil {
-		return false
+func Init(flogWriter LogReportCallback, log *Log, procId string, procName string, wg *sync.WaitGroup, done chan struct{}) bool {
+	logCh = make(chan LogPrinter, 300)
+
+	if nil != log {
+		logger = log
+	} else {
+		logger = &Log{}
 	}
 
-	go saveLoop()
+	ProcName = procName
+	ProcID = procId
+
+	go saveLoop(flogWriter, wg, done)
 
 	return true
 }
 
-func InitByPubFn(fn func(nodes []bhomebus.NetNode, topic string, data []byte, milliseconds int) int,
-				procId string, procName string) bool {
-	msgChan = make(chan []byte, 100)
-	ProcName = procName
-	ProcID = procId
-	pubFn = fn
-	if pubFn == nil {
-		return false
-	}
-
-	go saveLoop()
-
-	return true
-}
-
-func Save(level int, logType int, v ...interface{}) {
-	cache(level, logType, "", "", v)
-}
-
-func SaveManual(level int, logType int, userID string, userName string, v ...interface{}) {
-	cache(level, logType, userID, userName, v)
-}
-
-func cache(level int, logType int, userID string, userName string, fmtArgs []interface{}) {
-	// Format with Sprint, Sprintf, or neither.
-	msg := ""
-	if len(fmtArgs) > 0 {
-		msg = fmt.Sprint(fmtArgs...)
-	}
-	fmt.Println(msg)
-
-	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)
+func SaveOperationLog(log *OperationLog, timeout time.Duration) {
+	if nil == log {
 		return
 	}
 
-	msgChan <- data
+	log.ProcName = ProcName
+	log.ProcID = ProcID
+
+	deliverLog(log, timeout)
 }
 
-const (
-	LogSaveTopic = "logSaveTopic"
-)
+func SaveScheduleLog(category, level int, timeout time.Duration, v ...interface{}) {
+	msg := ""
+	if len(v) > 0 {
+		msg = fmt.Sprint(v...)
+	}
 
-func saveLoop() {
-	for {
-		select {
-		case data := <- msgChan:
-			var nodes []bhomebus.NetNode
-			nodes = append(nodes, bhomebus.NetNode{})
-			if bhSock != nil {
-				bhSock.PubTimeout(nodes, LogSaveTopic, data, 1000)
-			} else if pubFn != nil {
-				pubFn(nodes, LogSaveTopic, data, 1000)
-			} else {
-				fmt.Println("bhSock nil and pubFn nil")
-			}
+	if msg == "" {
+		return
+	}
 
-		default:
-			time.Sleep(10*time.Millisecond)
+	log := &ScheduleLog{
+		Timestamp: time.Now().Unix(),
+		ProcName:  ProcName,
+		ProcID:    ProcID,
+		Level:     level,
+		Type:      category,
+		Info:      msg,
+	}
+
+	deliverLog(log, timeout)
+}
+
+func SaveRuleServerLog(ruleServerPushLog RuleServerPushLog, timeout time.Duration) {
+	deliverLog(&ruleServerPushLog, timeout)
+}
+
+func deliverLog(l LogPrinter, timeout time.Duration) {
+	select {
+	case logCh <- l:
+		return
+	case <-time.After(timeout):
+		var info string
+		b, err := l.Marshal()
+		if nil == err {
+			info = string(b)
 		}
+		logger.Fatal("SaveScheduleLog failed to save log", info, l.Topic())
 	}
 }
 
+//func Save(level int, logType int, v ...interface{}) {
+//	cache(level, logType, "", "", v)
+//}
+//
+//func SaveManual(level int, logType int, userID string, userName string, v ...interface{}) {
+//	cache(level, logType, userID, userName, v)
+//}
+//
+//func cache(level int, logType int, userID string, userName string, fmtArgs []interface{}) {
+//	// Format with Sprint, Sprintf, or neither.
+//	msg := ""
+//	if len(fmtArgs) > 0 {
+//		msg = fmt.Sprint(fmtArgs...)
+//	}
+//	fmt.Println(msg)
+//
+//	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 (
+	OperationLogTopic  = "operationLogSaveTopic"
+	ScheduleLogTopic   = "scheduleLogSaveTopic"
+	RuleServerLogTopic = "ruleServerLogSaveTopic"
+	VaSystemLogTopic   = "VaSystemLogSaveTopic"
+)
+
+func saveLoop(logCallback LogReportCallback, wg *sync.WaitGroup, done chan struct{}) {
+	defer wg.Done()
+
+	if nil == logCallback {
+		return
+	}
+
+	for {
+		select {
+		case <-done:
+			return
+		case log := <-logCh:
+			payload, err := log.Marshal()
+			if err != nil {
+				logger.Error("failed to Marshal", log)
+			} else {
+				var nodes []bhome_msg.BHAddress
+				nodes = append(nodes, bhome_msg.BHAddress{})
+
+				reg := &LogRegister{
+					nodes,
+					log.Topic(),
+					payload,
+				}
+
+				logCallback(reg)
+			}
+		}
+	}
+}

--
Gitblit v1.8.0