package log import ( "io" "log/slog" "os" "sync" ) var historyList *logHistoryList func GetTailsOf(num int) []string { if historyList == nil { return nil } return historyList.GetTailsOf(num) } // 初始化IOT日志配置和历史纪录 func InitLog() { level := slog.LevelInfo historyList = newLogHistoryList(1000) // 最多保存1000条(根据情况调整) w := newIotLogWriter(historyList) slog.SetDefault(slog.New(slog.NewJSONHandler(w, &slog.HandlerOptions{ Level: level, AddSource: false, }))) } type iotLogWriter struct { io.Writer logs *logHistoryList } // 输出到Stdout func newIotLogWriter(logs *logHistoryList) *iotLogWriter { return &iotLogWriter{Writer: os.Stdout, logs: logs} } func (w *iotLogWriter) Write(p []byte) (n int, err error) { w.logs.Add(string(p)) return w.Writer.Write(p) } type logHistoryList struct { logs []string capacity int mutex sync.Mutex } func newLogHistoryList(capacity int) *logHistoryList { return &logHistoryList{ logs: make([]string, capacity), capacity: capacity, } } func (cl *logHistoryList) Add(item string) { cl.mutex.Lock() defer cl.mutex.Unlock() if len(cl.logs) >= cl.capacity { // 如果容量已满,删除最早的元素 cl.logs = cl.logs[1:] } cl.logs = append(cl.logs, item) } func (cl *logHistoryList) Len() int { cl.mutex.Lock() defer cl.mutex.Unlock() return len(cl.logs) } // 获取最新的num条记录 func (cl *logHistoryList) GetTailsOf(num int) []string { cl.mutex.Lock() defer cl.mutex.Unlock() end := len(cl.logs) start := end - num if start < 0 { start = 0 } return cl.logs[start:end] }