Skip to content

Commit

Permalink
reduced log rotation memory usage
Browse files Browse the repository at this point in the history
  • Loading branch information
marcopeocchi committed Sep 18, 2024
1 parent 64fbdbb commit 38da65a
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 33 deletions.
59 changes: 26 additions & 33 deletions server/logging/file_logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,23 @@ package logging
import (
"compress/gzip"
"io"
"log/slog"
"os"
"strings"
"sync"
"time"
)

/*
File base logger with log-rotate capabilities.
The rotate process must be initiated from an external goroutine.
implements io.Writer interface
After rotation the previous logs file are compressed with gzip algorithm.
File base logger with log-rotate capabilities.
The rotate process must be initiated from an external goroutine.
The rotated log follows this naming: [filename].UTC time.gz
*/
After rotation the previous logs file are compressed with gzip algorithm.
// implements io.Writer interface
The rotated log follows this naming: [filename].UTC time.gz
*/
type LogRotateWriter struct {
mu sync.Mutex
fd *os.File
Expand All @@ -40,50 +42,41 @@ func (w *LogRotateWriter) Write(b []byte) (int, error) {
}

func (w *LogRotateWriter) Rotate() error {
var err error
slog.Info("started log rotation")

w.mu.Lock()

gzFile, err := os.Create(w.filename + "." + time.Now().Format(time.RFC3339) + ".gz")
gzFile, err := os.Create(strings.TrimSuffix(w.filename, ".log") + "-" + time.Now().Format(time.RFC3339) + ".log.gz")
if err != nil {
return err
}

data, err := io.ReadAll(w.fd)
if err != nil {
return err
}
zw := gzip.NewWriter(gzFile)

defer func() {
w.mu.Unlock()
w.gzipLog(gzFile, &data)
zw.Close()
zw.Flush()
gzFile.Close()
}()

_, err = os.Stat(w.filename)
if err != nil {
if _, err := os.Stat(w.filename); err != nil {
return err
}

if w.fd != nil {
err = w.fd.Close()
w.fd = nil
if err != nil {
return err
}
}
fd, _ := os.Open(w.filename)
io.Copy(zw, fd)
fd.Close()

err = os.Remove(w.filename)
if err != nil {
w.fd.Close()

if err := os.Remove(w.filename); err != nil {
return err
}

w.fd, err = os.Create(w.filename)
return err
}
w.fd, _ = os.Create(w.filename)

func (w *LogRotateWriter) gzipLog(wr io.Writer, data *[]byte) error {
if _, err := gzip.NewWriter(wr).Write(*data); err != nil {
return err
}
w.mu.Unlock()
slog.Info("ended log rotation")

return nil
return err
}
2 changes: 2 additions & 0 deletions server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ func RunBlocking(rc *RunConfig) {
panic(err)
}

defer logger.Rotate()

go func() {
for {
time.Sleep(time.Hour * 24)
Expand Down

0 comments on commit 38da65a

Please sign in to comment.