重构:优化记录格式并修复核心功能

- 修改记录存储格式为 [4B len][8B offset][4B CRC][16B UUID][data]
- 修复 TopicProcessor 中 WaitGroup 使用错误导致 handler 不执行的问题
- 修复写入保护逻辑,避免 dirtyOffset=-1 时误判为写入中
- 添加统计信息定期持久化功能
- 改进 UTF-8 字符截断处理,防止 CJK 字符乱码
- 优化 Web UI:显示人类可读的文件大小,支持点击外部关闭弹窗
- 重构示例代码,添加 webui 和 webui_integration 示例

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2025-10-04 17:54:49 +08:00
parent 955a467248
commit 810664eb12
18 changed files with 1810 additions and 1170 deletions

140
example/webui/README.md Normal file
View File

@@ -0,0 +1,140 @@
# Seqlog Web UI 示例
这个示例展示了如何使用 seqlog 的内置 Web UI 功能。
## 特性
- **零编译前端**:使用 Vue 3 和 Tailwind CSS CDN无需前端构建步骤
- **实时日志查看**:查看多个 topic 的日志记录
- **统计信息**:实时显示每个 topic 的统计数据
- **日志查询**:支持查询最早、最新的日志记录
- **状态追踪**:显示日志的处理状态(待处理、处理中、已处理)
- **灵活集成**:可以集成到现有的 HTTP 服务器或其他框架
## 运行示例
```bash
cd example/webui
go run main.go
```
然后在浏览器中访问 http://localhost:8080
## API 端点
Web UI 提供以下 API 端点:
- `GET /api/topics` - 获取所有 topic 列表
- `GET /api/logs?topic=xxx&count=N` - 查询最新的 N 条日志(从最后一条向前查询)
- `GET /api/logs/first?topic=xxx&count=N` - 查询从第一条开始的 N 条日志(从索引 0 向后查询)
- `GET /api/logs/last?topic=xxx&count=N` - 查询最后的 N 条日志(从最后一条向前查询)
- `GET /api/stats?topic=xxx` - 获取指定 topic 的统计信息
## 使用方式
### 方式 1独立 Web UI 服务器
最简单的方式,直接启动一个独立的 Web UI 服务器:
```go
import "code.tczkiot.com/seqlog"
// 创建 LogHub
hub := seqlog.NewLogHub("./logs", logger, handler)
// 启动服务
hub.Start()
// 启动 Web UI会阻塞
hub.ServeUI(":8080")
```
如果需要在后台运行 Web UI
```go
go func() {
if err := hub.ServeUI(":8080"); err != nil {
logger.Error("Web UI 错误", "error", err)
}
}()
```
### 方式 2集成到现有 HTTP 服务器
如果你已经有一个 HTTP 服务器,可以将 Web UI 集成到现有的 ServeMux
```go
import (
"net/http"
"code.tczkiot.com/seqlog"
)
// 创建 LogHub
hub := seqlog.NewLogHub("./logs", logger, handler)
hub.Start()
// 创建自己的 ServeMux
mux := http.NewServeMux()
// 注册业务端点
mux.HandleFunc("/api/users", handleUsers)
mux.HandleFunc("/health", handleHealth)
// 注册 seqlog Web UI 到根路径
hub.RegisterWebUIRoutes(mux)
// 启动服务器
http.ListenAndServe(":8080", mux)
```
### 方式 3集成到子路径
如果你想将 Web UI 放在子路径下(比如 `/logs/`
```go
// 创建主 ServeMux
mux := http.NewServeMux()
// 注册业务端点
mux.HandleFunc("/health", handleHealth)
// 创建 Web UI 的 ServeMux
logsMux := http.NewServeMux()
hub.RegisterWebUIRoutes(logsMux)
// 挂载到 /logs/ 路径
mux.Handle("/logs/", http.StripPrefix("/logs", logsMux))
// 启动服务器
http.ListenAndServe(":8080", mux)
```
访问 http://localhost:8080/logs/ 查看 Web UI。
完整的集成示例请参考 [example/webui_integration](../webui_integration/main.go)。
### 方式 4集成到其他 Web 框架
对于 gin、echo 等框架,可以通过适配器集成:
```go
// Gin 框架示例
import (
"github.com/gin-gonic/gin"
"net/http"
)
r := gin.Default()
// 业务路由
r.GET("/api/users", handleUsers)
// 创建 seqlog Web UI 的 ServeMux
logsMux := http.NewServeMux()
hub.RegisterWebUIRoutes(logsMux)
// 使用 gin.WrapH 包装 http.Handler
r.Any("/logs/*path", gin.WrapH(http.StripPrefix("/logs", logsMux)))
r.Run(":8080")
```

114
example/webui/main.go Normal file
View File

@@ -0,0 +1,114 @@
package main
import (
"fmt"
"log/slog"
"math/rand"
"os"
"strings"
"sync"
"time"
"unicode/utf8"
"code.tczkiot.com/seqlog"
)
func main() {
// 创建日志目录
baseDir := "./logs"
if err := os.MkdirAll(baseDir, 0755); err != nil {
panic(err)
}
// 创建 LogHub
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.LevelInfo,
}))
// 自定义处理器:打印处理的记录
handler := func(topic string, record *seqlog.Record) error {
previewSize := min(int(record.Len), 100)
validPreviewSize := previewSize
if previewSize > 0 && previewSize < int(record.Len) {
// 只有在截断的情况下才需要检查
// 从后往前最多检查 3 个字节,找到最后一个完整的 UTF-8 字符边界
for i := 0; i < 3 && validPreviewSize > 0; i++ {
if utf8.Valid(record.Data[:validPreviewSize]) {
break
}
validPreviewSize--
}
}
fmt.Printf("[%s] 处理记录: %s\n", topic, string(record.Data[:validPreviewSize]))
return nil
}
hub := seqlog.NewLogHub(baseDir, logger, handler)
// 启动 LogHub会自动发现和启动所有 topic
if err := hub.Start(); err != nil {
panic(err)
}
defer hub.Stop()
// topic 列表(会在第一次写入时自动创建)
topics := []string{"app", "system", "access"}
// 在后台启动 Web UI 服务器
go func() {
fmt.Println("启动 Web UI 服务器: http://localhost:8080")
if err := hub.ServeUI(":8080"); err != nil {
fmt.Printf("Web UI 服务器错误: %v\n", err)
}
}()
// 生成随机大小的数据2KB 到 10MB
generateRandomData := func(minSize, maxSize int) []byte {
size := minSize + rand.Intn(maxSize-minSize)
// 使用重复字符填充,模拟实际日志内容
return []byte(strings.Repeat("X", size))
}
// 启动多个并发写入器(提高并发数)
var wg sync.WaitGroup
concurrentWriters := 10 // 10 个并发写入器
for i := range concurrentWriters {
wg.Add(1)
go func(writerID int) {
defer wg.Done()
count := 0
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop()
for range ticker.C {
count++
// 随机选择 topic
topic := topics[rand.Intn(len(topics))]
// 生成随机大小的数据2KB 到 2MB
minSize := 2 * 1024 // 2KB
maxSize := 2 * 1024 * 1024 // 2MB
randomData := generateRandomData(minSize, maxSize)
// 组合消息头和随机数据
message := fmt.Sprintf("[Writer-%d] 日志 #%d - %s - 大小: %d bytes\n",
writerID, count, time.Now().Format(time.RFC3339), len(randomData))
fullData := append([]byte(message), randomData...)
if _, err := hub.Write(topic, fullData); err != nil {
fmt.Printf("写入失败: %v\n", err)
}
}
}(i)
}
// 等待用户中断
fmt.Println("\n==== Seqlog Web UI 示例 ====")
fmt.Println("访问 http://localhost:8080 查看 Web UI")
fmt.Println("按 Ctrl+C 退出")
// 阻塞主线程
select {}
}