refactor: refine byte pools usage and fix memory leak in rules

This commit is contained in:
yusing
2025-10-15 23:53:26 +08:00
parent 2b4c39a79e
commit 44536139c1
7 changed files with 73 additions and 42 deletions

View File

@@ -157,12 +157,12 @@ func (l *AccessLogger) Log(req *http.Request, res *http.Response) {
}
line := lineBufPool.Get()
defer lineBufPool.Put(line)
line = l.AppendRequestLog(line, req, res)
if line[len(line)-1] != '\n' {
line = append(line, '\n')
}
l.write(line)
lineBufPool.Put(line)
}
func (l *AccessLogger) LogError(req *http.Request, err error) {
@@ -171,12 +171,12 @@ func (l *AccessLogger) LogError(req *http.Request, err error) {
func (l *AccessLogger) LogACL(info *maxmind.IPInfo, blocked bool) {
line := lineBufPool.Get()
defer lineBufPool.Put(line)
line = l.AppendACLLog(line, info, blocked)
if line[len(line)-1] != '\n' {
line = append(line, '\n')
}
l.write(line)
lineBufPool.Put(line)
}
func (l *AccessLogger) ShouldRotate() bool {

View File

@@ -4,6 +4,7 @@ import (
"bytes"
"errors"
"io"
"slices"
"time"
"github.com/rs/zerolog"
@@ -167,14 +168,16 @@ func rotateLogFileByPolicy(file supportRotate, config *Retention, result *Rotate
// Read each line and write it to the beginning of the file
writePos := int64(0)
buf := rotateBytePool.Get()
defer rotateBytePool.Put(buf)
defer func() {
rotateBytePool.Put(buf)
}()
// in reverse order to keep the order of the lines (from old to new)
for i := len(linesToKeep) - 1; i >= 0; i-- {
line := linesToKeep[i]
n := line.Size
if cap(buf) < int(n) {
buf = make([]byte, n)
buf = slices.Grow(buf, int(n)-cap(buf))
}
buf = buf[:n]