优化日志系统

This commit is contained in:
yml2213
2026-06-19 12:10:55 +08:00
parent 1805edc63a
commit 59b9dd12ef
11 changed files with 232 additions and 66 deletions
+66 -4
View File
@@ -1,6 +1,7 @@
package main
import (
"fmt"
"io"
"log"
"os"
@@ -61,12 +62,17 @@ func (s *memoryLogStore) Write(p []byte) (int, error) {
if strings.TrimSpace(line) == "" {
continue
}
category, level := parseLogMeta(line)
if level == "" {
level = detectLogLevel(line)
}
s.nextID++
s.entries = append(s.entries, LogEntry{
ID: s.nextID,
Time: time.Now().In(cst).Format("2006-01-02 15:04:05.000"),
Level: detectLogLevel(line),
Message: line,
ID: s.nextID,
Time: time.Now().In(cst).Format("2006-01-02 15:04:05.000"),
Level: level,
Category: category,
Message: line,
})
if len(s.entries) > s.max {
copy(s.entries, s.entries[len(s.entries)-s.max:])
@@ -76,6 +82,54 @@ func (s *memoryLogStore) Write(p []byte) (int, error) {
return len(p), nil
}
// logEvent 输出带分类和级别的结构化文本日志。
func logEvent(category, level, format string, args ...any) {
if category == "" {
category = "系统"
}
if level == "" {
level = "info"
}
log.Printf("[%s][%s] %s", category, level, fmt.Sprintf(format, args...))
}
// parseLogMeta 从标准日志行中提取类似 [网络][warn] 的分类和级别。
func parseLogMeta(line string) (string, string) {
idx := strings.Index(line, "[")
if idx < 0 {
return "", ""
}
category, rest, ok := cutBracket(line[idx:])
if !ok {
return "", ""
}
level, _, ok := cutBracket(rest)
if !ok || !isLogLevel(level) {
return category, ""
}
return category, level
}
func cutBracket(s string) (string, string, bool) {
if !strings.HasPrefix(s, "[") {
return "", s, false
}
end := strings.Index(s, "]")
if end <= 1 {
return "", s, false
}
return s[1:end], s[end+1:], true
}
func isLogLevel(level string) bool {
switch strings.ToLower(level) {
case "success", "error", "warn", "info":
return true
default:
return false
}
}
// setFilePath 保存当前日志文件路径,供前端展示或排查使用。
func (s *memoryLogStore) setFilePath(path string) {
s.mu.Lock()
@@ -108,6 +162,14 @@ func (s *memoryLogStore) FilePath() string {
func detectLogLevel(line string) string {
lower := strings.ToLower(line)
switch {
case strings.Contains(lower, "[success]"):
return "success"
case strings.Contains(lower, "[error]"):
return "error"
case strings.Contains(lower, "[warn]"):
return "warn"
case strings.Contains(lower, "[info]"):
return "info"
case strings.Contains(line, "成功"):
return "success"
case strings.Contains(line, "失败") || strings.Contains(line, "错误") || strings.Contains(lower, "error") || strings.Contains(lower, "panic"):