备份、隧道生命周期、日志、会话与设置项存在一批「静默失效」问题,本次一并收敛。 正确性: - 备份归档补上 session_secret 与 frp 配置。缺密钥时换机恢复后库里所有凭据都解不开, 界面表现为「配置都在、一执行就报解密失败」;同时支持口令加密(scrypt + AES-256-GCM)。 - 修复「立即备份」必失败:tar 头用的是遍历时的文件尺寸,而 logs、frpc 配置在打包期间 还在增长,读出的字节多于声明值导致 archive/tar 报错、整份备份作废。改为打开后重新 取尺寸并用 LimitReader 兜住,被截短时补零保持条目结构完整。 - 数据库改用 VACUUM INTO 生成一致性快照。直接打包正在写入的 SQLite 文件可能得到 结构完整但内容自相矛盾的副本,恢复后才暴露。 - Cloudflare 启动改用 StartAuto,Shutdown 显式 StopAll,子进程绑定应用 ctx。此前 重启会把用户手动停掉的隧道重新拉起,退出也可能留下孤儿进程。 - Nginx 访问/错误日志加轮转(200MB 阈值、gzip 归档、USR1 重开),读取改为从文件尾 分块倒读,并跨当日归档统计。此前日志只增不减,读接口每次全量扫描。 - 过期会话改由日任务清理;删除反代规则时同步清掉流量累计,避免同名规则重建继承旧读数。 - 启动加就绪门:Nginx bootstrap 完成后再放行 FRP 对账、Agent 隧道与 Cloudflare 自启。 设置项: - 新增设置项注册表(internal/settings/registry.go),白名单与默认值从它派生, 并记录每个键的消费者,防止再出现「界面能改、后端没人读」的黑洞设置。 - 接上三个此前不生效的设置项:timezone(启动与保存时应用到 time.Local)、 theme(后端为权威源,挂载时覆盖本地偏好、顶栏切换回写)、log_retention_days (控制日志归档保留天数)。 工程质量: - gofmt 全量格式化 23 个历史文件,CI 增加格式化门禁。 - 前端引入 ESLint(flat config)与 lint 脚本,CI 增加 lint 步骤;顺带修掉 logDisplay 的 let→const 与 LogsView 模板内直接改 prop 两处问题。 - 删除无引用的 pnpm-lock.yaml,prototype/ 加入忽略列表。 - 打包版本对齐:Docker manifest 同步到 2.0.0,CI 校验 VERSION 与 package.json 一致。 验证:gofmt 0 文件、go vet、go test ./...、npm run lint/typecheck/test/build 全绿。 Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
+137
-28
@@ -2,10 +2,14 @@ package logstore
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"compress/gzip"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -298,16 +302,9 @@ func hourlyAccessCountsForDay(path string, day time.Time) ([]int, []string) {
|
||||
counts := make([]int, hourlyBucketCount)
|
||||
labels := calendarHourlyLabels()
|
||||
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return counts, labels
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
scanner := bufio.NewScanner(file)
|
||||
scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
|
||||
for scanner.Scan() {
|
||||
entry, ok := parseAccess(scanner.Text())
|
||||
// 轮转后的历史内容在归档文件里:只读当前文件会让「今日统计」在轮转后突然掉一半。
|
||||
for _, line := range accessLinesForDay(path, day) {
|
||||
entry, ok := parseAccess(line)
|
||||
if !ok || !isDashboardAccess(entry) {
|
||||
continue
|
||||
}
|
||||
@@ -324,6 +321,75 @@ func hourlyAccessCountsForDay(path string, day time.Time) ([]int, []string) {
|
||||
return counts, labels
|
||||
}
|
||||
|
||||
// accessLinesForDay 返回某天的原始日志行:当前文件 + 该日期的归档文件。
|
||||
// 只挑文件名里带目标日期的归档,避免把几个月的归档都解开。
|
||||
func accessLinesForDay(path string, day time.Time) []string {
|
||||
var out []string
|
||||
stamp := day.Format("20060102")
|
||||
for _, archive := range archivesForDay(path, stamp) {
|
||||
out = append(out, readGzipLines(archive)...)
|
||||
}
|
||||
out = append(out, readFileLines(path)...)
|
||||
return out
|
||||
}
|
||||
|
||||
// archivesForDay 列出与目标日期匹配的归档(access-20261024-1305.log.gz):
|
||||
// 文件名里的日期是按轮转时刻取的,所以既可能属于当天,也可能属于前一天跨零点的那一段。
|
||||
func archivesForDay(path, day string) []string {
|
||||
dir := filepath.Dir(path)
|
||||
base := strings.TrimSuffix(filepath.Base(path), ".log")
|
||||
prefix := base + "-" + day
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
out := make([]string, 0, 4)
|
||||
for _, entry := range entries {
|
||||
name := entry.Name()
|
||||
if entry.IsDir() || !strings.HasPrefix(name, prefix) || !strings.HasSuffix(name, ".log.gz") {
|
||||
continue
|
||||
}
|
||||
out = append(out, filepath.Join(dir, name))
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
func readFileLines(path string) []string {
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
defer file.Close()
|
||||
var lines []string
|
||||
scanner := bufio.NewScanner(file)
|
||||
scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
|
||||
for scanner.Scan() {
|
||||
lines = append(lines, scanner.Text())
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
func readGzipLines(path string) []string {
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
defer file.Close()
|
||||
gz, err := gzip.NewReader(file)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
defer gz.Close()
|
||||
var lines []string
|
||||
scanner := bufio.NewScanner(gz)
|
||||
scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
|
||||
for scanner.Scan() {
|
||||
lines = append(lines, scanner.Text())
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
func calendarHourlyLabels() []string {
|
||||
labels := make([]string, hourlyBucketCount)
|
||||
for i := 0; i < hourlyBucketCount; i++ {
|
||||
@@ -358,17 +424,10 @@ func CountTodayAccess(path string) (total int, errors int, avgMs float64) {
|
||||
}
|
||||
|
||||
func CountAccessForDay(path string, day time.Time) (total int, errors int, avgMs float64) {
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return 0, 0, 0
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
var sum float64
|
||||
scanner := bufio.NewScanner(file)
|
||||
scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
|
||||
for scanner.Scan() {
|
||||
entry, ok := parseAccess(scanner.Text())
|
||||
// 与小时曲线一致:轮转后的内容在归档里,只扫当前文件会漏掉当天早些时候的请求
|
||||
for _, line := range accessLinesForDay(path, day) {
|
||||
entry, ok := parseAccess(line)
|
||||
if !ok || !isDashboardAccess(entry) {
|
||||
continue
|
||||
}
|
||||
@@ -388,7 +447,14 @@ func CountAccessForDay(path string, day time.Time) (total int, errors int, avgMs
|
||||
return total, errors, avgMs
|
||||
}
|
||||
|
||||
// tailLines 返回文件末尾的至多 max 行(保持原顺序,旧→新)。
|
||||
//
|
||||
// 之所以从文件尾往前读:日志可能上到几百 MB,而调用方只要最后几十行。
|
||||
// 顺序扫描等于每刷新一次页面就把整个文件读一遍,NAS 这种长期运行的机器上很吃亏。
|
||||
func tailLines(path string, max int) ([]string, error) {
|
||||
if max <= 0 {
|
||||
return nil, nil
|
||||
}
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
@@ -398,16 +464,59 @@ func tailLines(path string, max int) ([]string, error) {
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
scanner := bufio.NewScanner(file)
|
||||
scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
|
||||
var lines []string
|
||||
for scanner.Scan() {
|
||||
lines = append(lines, scanner.Text())
|
||||
if len(lines) > max {
|
||||
lines = lines[1:]
|
||||
info, err := file.Stat()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
size := info.Size()
|
||||
if size == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// 从尾部往前读块,攒够 max 个换行就停。64KB 起步,最多扩到 8MB:
|
||||
// 单行上限 1MB(与 scanner 的上限一致),保证超长行不会被截断成多条。
|
||||
const (
|
||||
startChunk = 64 << 10
|
||||
maxChunk = 8 << 20
|
||||
)
|
||||
chunk := int64(startChunk)
|
||||
var tail []byte
|
||||
offset := size
|
||||
for offset > 0 {
|
||||
readSize := chunk
|
||||
if readSize > offset {
|
||||
readSize = offset
|
||||
}
|
||||
offset -= readSize
|
||||
buf := make([]byte, readSize)
|
||||
if _, err := file.ReadAt(buf, offset); err != nil && err != io.EOF {
|
||||
return nil, err
|
||||
}
|
||||
tail = append(buf, tail...)
|
||||
// 已攒到足够的行就不必继续往前读(末尾若没有换行,也算一行)
|
||||
if strings.Count(string(tail), "\n") > max {
|
||||
break
|
||||
}
|
||||
if chunk < maxChunk {
|
||||
chunk *= 2
|
||||
}
|
||||
}
|
||||
return lines, scanner.Err()
|
||||
|
||||
text := string(tail)
|
||||
if offset > 0 {
|
||||
// 从中间开始读时,第一行很可能是半行:丢掉它
|
||||
if i := strings.IndexByte(text, '\n'); i >= 0 {
|
||||
text = text[i+1:]
|
||||
}
|
||||
}
|
||||
lines := strings.Split(strings.TrimRight(text, "\n"), "\n")
|
||||
if len(lines) > max {
|
||||
lines = lines[len(lines)-max:]
|
||||
}
|
||||
if len(lines) == 1 && lines[0] == "" {
|
||||
return nil, nil
|
||||
}
|
||||
return lines, nil
|
||||
}
|
||||
|
||||
func asString(v any) string {
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
package logstore
|
||||
|
||||
import (
|
||||
"compress/gzip"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Nginx 自己不会轮转日志,长期运行的 NAS 上 access.log 会一直长。
|
||||
// 这里的策略刻意保持简单:
|
||||
// - 超过 MaxBytes 才轮转,避免一天切一堆小文件;
|
||||
// - 轮转时把 access.log 改名成 access-<时间戳>.log.gz,再让 Nginx 重开文件;
|
||||
// - 保留最近 Keep 份,更旧的删掉。
|
||||
//
|
||||
// 用「rename + 信号重开」而不是 truncate:truncate 会丢掉读侧(流量采集)还没读到的内容。
|
||||
const (
|
||||
// DefaultMaxBytes 单个日志文件的上限(200MB)。NAS 上反代日志增长很快,
|
||||
// 太大则读取接口变慢,太小则轮转频繁、压缩开销占比升高。
|
||||
DefaultMaxBytes int64 = 200 << 20
|
||||
// DefaultKeep 每个日志保留的归档份数。
|
||||
DefaultKeep = 5
|
||||
)
|
||||
|
||||
// Rotator 负责单个日志文件的轮转与清理。
|
||||
type Rotator struct {
|
||||
// Path 当前正在写入的日志路径(例如 <DataDir>/logs/access.log)
|
||||
Path string
|
||||
// MaxBytes 超过它就轮转;<= 0 用 DefaultMaxBytes
|
||||
MaxBytes int64
|
||||
// Keep 保留份数;<= 0 用 DefaultKeep
|
||||
Keep int
|
||||
// MaxAgeDays 归档保留天数;<= 0 表示不按时间清理(只按份数)。
|
||||
// 对应「设置 → 常规 → 日志保留天数」,填了才生效。
|
||||
MaxAgeDays int
|
||||
// reopen 通知写日志的进程重新打开文件(Nginx 用 USR1)
|
||||
reopen func() error
|
||||
}
|
||||
|
||||
// NewRotator 装配一个日志轮转器。reopen 用于通知写日志的进程重新打开文件
|
||||
// (Nginx 用 USR1);传 nil 表示该日志由本进程自己写,不需要重开。
|
||||
func NewRotator(path string, maxAgeDays int, reopen func() error) *Rotator {
|
||||
return &Rotator{Path: path, MaxAgeDays: maxAgeDays, reopen: reopen}
|
||||
}
|
||||
|
||||
// RotateIfNeeded 在文件超过阈值时轮转,返回是否真的轮转了。
|
||||
// 未超阈值时不产生任何副作用,可以安全地高频调用。
|
||||
func (r *Rotator) RotateIfNeeded(now time.Time) (bool, error) {
|
||||
info, err := os.Stat(r.Path)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
limit := r.MaxBytes
|
||||
if limit <= 0 {
|
||||
limit = DefaultMaxBytes
|
||||
}
|
||||
if info.Size() < limit {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
target := r.archivePath(now)
|
||||
if err := compressRename(r.Path, target); err != nil {
|
||||
return false, err
|
||||
}
|
||||
// 文件被改名后,Nginx 仍持有旧 inode 继续往里写。必须让它重开,
|
||||
// 否则新内容会写进已归档的那份文件,轮转等于没做。
|
||||
if r.reopen != nil {
|
||||
if err := r.reopen(); err != nil {
|
||||
return true, fmt.Errorf("日志已归档,但通知重开失败:%w", err)
|
||||
}
|
||||
}
|
||||
// 归档成功后再清理旧份数:清理失败不该让本轮轮转算失败
|
||||
r.prune()
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// archivePath 生成归档名:access.log → access-20261024-1305.log.gz。
|
||||
// 时间戳精确到分钟,同一分钟内重复轮转时补序号,避免覆盖。
|
||||
func (r *Rotator) archivePath(now time.Time) string {
|
||||
dir := filepath.Dir(r.Path)
|
||||
base := strings.TrimSuffix(filepath.Base(r.Path), ".log")
|
||||
stamp := now.Format("20060102-1504")
|
||||
candidate := filepath.Join(dir, fmt.Sprintf("%s-%s.log.gz", base, stamp))
|
||||
for i := 2; ; i++ {
|
||||
if _, err := os.Stat(candidate); os.IsNotExist(err) {
|
||||
return candidate
|
||||
}
|
||||
candidate = filepath.Join(dir, fmt.Sprintf("%s-%s-%d.log.gz", base, stamp, i))
|
||||
}
|
||||
}
|
||||
|
||||
// prune 先按保留天数删超期归档,再按份数保留最近的。
|
||||
// 两个条件都生效:天数保证「长期不轮转也不会无限留」,份数保证「高频轮转不会堆积」。
|
||||
func (r *Rotator) prune() {
|
||||
archives := r.archives()
|
||||
if r.MaxAgeDays > 0 {
|
||||
cutoff := time.Now().Add(-time.Duration(r.MaxAgeDays) * 24 * time.Hour)
|
||||
kept := archives[:0]
|
||||
for _, path := range archives {
|
||||
info, err := os.Stat(path)
|
||||
if err == nil && info.ModTime().Before(cutoff) {
|
||||
_ = os.Remove(path)
|
||||
continue
|
||||
}
|
||||
kept = append(kept, path)
|
||||
}
|
||||
archives = kept
|
||||
}
|
||||
keep := r.Keep
|
||||
if keep <= 0 {
|
||||
keep = DefaultKeep
|
||||
}
|
||||
for i := 0; i < len(archives)-keep; i++ {
|
||||
_ = os.Remove(archives[i])
|
||||
}
|
||||
}
|
||||
|
||||
// archives 列出该日志的归档文件,按旧→新排序。
|
||||
func (r *Rotator) archives() []string {
|
||||
dir := filepath.Dir(r.Path)
|
||||
base := strings.TrimSuffix(filepath.Base(r.Path), ".log")
|
||||
prefix := base + "-"
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
out := make([]string, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
name := entry.Name()
|
||||
if entry.IsDir() || !strings.HasPrefix(name, prefix) || !strings.HasSuffix(name, ".log.gz") {
|
||||
continue
|
||||
}
|
||||
out = append(out, filepath.Join(dir, name))
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// compressRename 把 src 压缩写到 dst,成功后删除 src。
|
||||
// 先写 .tmp 再改名:压缩中途失败不会留下一个看起来能用的归档。
|
||||
func compressRename(src, dst string) error {
|
||||
in, err := os.Open(src)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tmp := dst + ".tmp"
|
||||
out, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o640)
|
||||
if err != nil {
|
||||
_ = in.Close()
|
||||
return err
|
||||
}
|
||||
gz := gzip.NewWriter(out)
|
||||
if _, err := io.Copy(gz, in); err != nil {
|
||||
_ = gz.Close()
|
||||
_ = out.Close()
|
||||
_ = in.Close()
|
||||
_ = os.Remove(tmp)
|
||||
return err
|
||||
}
|
||||
// 关闭顺序与错误都要检查:gzip 的尾部写在 Close 里,漏了就是半截归档
|
||||
if err := gz.Close(); err != nil {
|
||||
_ = out.Close()
|
||||
_ = in.Close()
|
||||
_ = os.Remove(tmp)
|
||||
return err
|
||||
}
|
||||
if err := out.Close(); err != nil {
|
||||
_ = in.Close()
|
||||
_ = os.Remove(tmp)
|
||||
return err
|
||||
}
|
||||
// 必须显式关闭源文件再删:Windows 上句柄没放掉时 Remove/改名都会失败
|
||||
if err := in.Close(); err != nil {
|
||||
_ = os.Remove(tmp)
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(tmp, dst); err != nil {
|
||||
_ = os.Remove(tmp)
|
||||
return err
|
||||
}
|
||||
// 归档成功才删原文件;顺序反了会在压缩失败时丢日志
|
||||
return os.Remove(src)
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package logstore
|
||||
|
||||
import (
|
||||
"compress/gzip"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestRotateIfNeededSkipsSmallFile:未超阈值不能产生任何副作用,否则每小时一次的
|
||||
// 定时任务会把日志切成无数小文件。
|
||||
func TestRotateIfNeededSkipsSmallFile(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "access.log")
|
||||
if err := os.WriteFile(path, []byte("small\n"), 0o640); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reopened := 0
|
||||
r := NewRotator(path, 0, func() error {
|
||||
reopened++
|
||||
return nil
|
||||
})
|
||||
rotated, err := r.RotateIfNeeded(time.Now())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if rotated {
|
||||
t.Fatal("未超阈值不应轮转")
|
||||
}
|
||||
if reopened != 0 {
|
||||
t.Fatal("未轮转时不应通知重开日志")
|
||||
}
|
||||
if _, err := os.Stat(path); err != nil {
|
||||
t.Fatalf("原文件应保持不动:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRotateCompressesAndReopens:超阈值时要归档成 .gz、通知进程重开文件、并删掉原文件。
|
||||
func TestRotateCompressesAndReopens(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "access.log")
|
||||
content := strings.Repeat("2026-10-24T10:00:00+08:00 a.example.com 18080 GET / 200 0.010 1.2.3.4 10.0.0.2:80 100 200\n", 200)
|
||||
if err := os.WriteFile(path, []byte(content), 0o640); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
reopened := 0
|
||||
r := NewRotator(path, 0, func() error {
|
||||
reopened++
|
||||
return nil
|
||||
})
|
||||
r.MaxBytes = 1024 // 强制触发
|
||||
now := time.Date(2026, 10, 24, 13, 5, 0, 0, time.Local)
|
||||
rotated, err := r.RotateIfNeeded(now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !rotated {
|
||||
t.Fatal("超过阈值应轮转")
|
||||
}
|
||||
if reopened != 1 {
|
||||
t.Fatalf("轮转后必须通知重开日志,实际调用 %d 次", reopened)
|
||||
}
|
||||
if _, err := os.Stat(path); !os.IsNotExist(err) {
|
||||
t.Fatal("轮转后原文件应被移走")
|
||||
}
|
||||
|
||||
archive := filepath.Join(dir, "access-20261024-1305.log.gz")
|
||||
file, err := os.Open(archive)
|
||||
if err != nil {
|
||||
t.Fatalf("应生成归档文件 %s:%v", archive, err)
|
||||
}
|
||||
defer file.Close()
|
||||
gz, err := gzip.NewReader(file)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer gz.Close()
|
||||
data, err := io.ReadAll(gz)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(data) != content {
|
||||
t.Fatalf("归档内容应与原文件一致:got %d bytes want %d", len(data), len(content))
|
||||
}
|
||||
}
|
||||
|
||||
// TestRotatePrunesOldArchives:归档份数与保留天数都要生效。
|
||||
func TestRotatePrunesOldArchives(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "access.log")
|
||||
|
||||
// 造 3 个既有归档,其中 2 个已经超期
|
||||
old := time.Now().Add(-40 * 24 * time.Hour)
|
||||
stale := []string{"access-20200101-0000.log.gz", "access-20200102-0000.log.gz"}
|
||||
for _, name := range stale {
|
||||
p := filepath.Join(dir, name)
|
||||
if err := os.WriteFile(p, []byte("x"), 0o640); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Chtimes(p, old, old); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
fresh := filepath.Join(dir, "access-20261024-1200.log.gz")
|
||||
if err := os.WriteFile(fresh, []byte("x"), 0o640); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := os.WriteFile(path, []byte(strings.Repeat("line\n", 500)), 0o640); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := NewRotator(path, 7, nil) // 保留 7 天
|
||||
r.MaxBytes = 1024
|
||||
if _, err := r.RotateIfNeeded(time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
for _, name := range stale {
|
||||
if _, err := os.Stat(filepath.Join(dir, name)); !os.IsNotExist(err) {
|
||||
t.Fatalf("超过保留天数的归档应被删除:%s", name)
|
||||
}
|
||||
}
|
||||
if _, err := os.Stat(fresh); err != nil {
|
||||
t.Fatalf("未超期的归档应保留:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTailLinesReadsFromEnd:尾部读取既要拿对最后几行,也不能因为文件很大而读全量。
|
||||
func TestTailLinesReadsFromEnd(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "access.log")
|
||||
var b strings.Builder
|
||||
for i := 0; i < 5000; i++ {
|
||||
b.WriteString("line-")
|
||||
b.WriteString(strings.Repeat("x", 20))
|
||||
b.WriteString("\n")
|
||||
}
|
||||
b.WriteString("last-line-a\nlast-line-b\n")
|
||||
if err := os.WriteFile(path, []byte(b.String()), 0o640); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
lines, err := tailLines(path, 3)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []string{strings.TrimSpace("line-xxxxxxxxxxxxxxxxxxxx"), "last-line-a", "last-line-b"}
|
||||
if len(lines) != len(want) {
|
||||
t.Fatalf("应返回 3 行,实际 %d:%v", len(lines), lines)
|
||||
}
|
||||
for i := range want {
|
||||
if lines[i] != want[i] {
|
||||
t.Fatalf("第 %d 行不符:got %q want %q", i, lines[i], want[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestTailLinesSingleLongLine:单行超过初始块大小时不能被截断成多行。
|
||||
func TestTailLinesSingleLongLine(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "access.log")
|
||||
long := strings.Repeat("y", 300*1024)
|
||||
if err := os.WriteFile(path, []byte(long+"\n"), 0o640); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lines, err := tailLines(path, 5)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(lines) != 1 || lines[0] != long {
|
||||
t.Fatalf("超长单行应完整返回,实际 %d 行(首行长度 %d)", len(lines), len(lines[0]))
|
||||
}
|
||||
}
|
||||
|
||||
// TestTailLinesMissingFile:日志还没产生时返回空而不是报错。
|
||||
func TestTailLinesMissingFile(t *testing.T) {
|
||||
lines, err := tailLines(filepath.Join(t.TempDir(), "nope.log"), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("文件不存在不应报错:%v", err)
|
||||
}
|
||||
if len(lines) != 0 {
|
||||
t.Fatalf("应返回空行列表,实际 %v", lines)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user