重构: 日志系统结构化,消除字符串反解析

旧链路:LogEvent→log.Print→logFileWriter→MemoryLogStore.Write
再用 ParseLogLine 字符串切割把分类/级别/账号反解析回来,格式一调就崩。

新链路:LogEvent 直构 LogEntry(Time/Level/Category/Account 直接填值),
经 sink 分发到内存(同步)/文件(异步)/终端。Message 仍用 formatLogLine
渲染保持文件文本格式与前端清理逻辑兼容。

- MemoryLogStore 新增 Append(entry) 替代 Write 的字符串解析路径
- 删除 logFileWriter,新增 sink 统一管理三路输出
- 删除 log.SetOutput/log.Print 依赖
- 保留 ParseLogLine/DetectLogLevel/formatLogLine(AsyncLogWriter 丢弃
  统计与测试仍用),但 log_store 不再调用
- 新增 TestStructuredLogging 覆盖 LogEvent→sink→Append 链路与 minLevel 过滤
This commit is contained in:
yml2213
2026-07-29 12:52:26 +08:00
parent 7c2c5a61a6
commit b72a58fd57
3 changed files with 120 additions and 67 deletions
+11 -39
View File
@@ -1,15 +1,12 @@
package logger
import (
"strings"
"sync"
"time"
"douyu_go/internal/constants"
"douyu_go/internal/types"
)
// MemoryLogStore 内存日志缓冲,实现 io.Writer 接口。
// MemoryLogStore 内存日志缓冲,供前端增量拉取。
type MemoryLogStore struct {
mu sync.RWMutex
nextID int64
@@ -29,44 +26,19 @@ func NewMemoryLogStore(max int) *MemoryLogStore {
}
}
// Write 实现 io.Writer,把标准 log 输出转存为内存日志。
func (s *MemoryLogStore) Write(p []byte) (int, error) {
text := strings.TrimRight(string(p), "\r\n")
if text == "" {
return len(p), nil
}
// Append 追加一条结构化日志,由内部分配自增 ID。
// 超过容量时丢弃最旧的条目,保留最近的 max 条。
func (s *MemoryLogStore) Append(entry types.LogEntry) types.LogEntry {
s.mu.Lock()
defer s.mu.Unlock()
for _, line := range strings.Split(text, "\n") {
line = strings.TrimRight(line, "\r")
if strings.TrimSpace(line) == "" {
continue
}
meta := ParseLogLine(line)
category, level := meta.Category, meta.Level
if level == "" {
level = DetectLogLevel(line)
}
logTime := meta.Time
if logTime == "" {
logTime = time.Now().In(constants.CST).Format("2006-01-02 15:04:05.000")
}
s.nextID++
s.entries = append(s.entries, types.LogEntry{
ID: s.nextID,
Time: logTime,
Level: level,
Category: category,
Account: meta.Account,
Message: line,
})
if len(s.entries) > s.max {
copy(s.entries, s.entries[len(s.entries)-s.max:])
s.entries = s.entries[:s.max]
}
s.nextID++
entry.ID = s.nextID
s.entries = append(s.entries, entry)
if len(s.entries) > s.max {
copy(s.entries, s.entries[len(s.entries)-s.max:])
s.entries = s.entries[:s.max]
}
return len(p), nil
return entry
}
// SetFilePath 保存当前日志文件路径。