From 1c2fe8076b880bd26179e432cf7b2ca0d36179c3 Mon Sep 17 00:00:00 2001 From: Praveen Ravichandran Date: Thu, 19 May 2022 10:03:24 -0400 Subject: [PATCH] Enable log rotation --- logger.go | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ types.go | 5 +++-- 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/logger.go b/logger.go index e1ecc7e..e435b6a 100644 --- a/logger.go +++ b/logger.go @@ -6,6 +6,7 @@ import ( "log" "os" "runtime" + "time" "github.com/fatih/color" ) @@ -13,6 +14,7 @@ import ( var ( currentLogLevel LogLevel = LevelError logFilePath string = "logfile.txt" + maxSizeInBytes int64 = 5 * 1024 * 1024 ) // Init initializes a logger @@ -24,6 +26,9 @@ func Init(opts *LoggerOptions) (func(), error) { if opts.LogFilePath != "" { logFilePath = opts.LogFilePath } + if opts.LogFileMaxSize > 0 { + maxSizeInBytes = opts.LogFileMaxSize + } } f, err := os.OpenFile(logFilePath, os.O_APPEND|os.O_RDWR|os.O_CREATE, 0755) if err != nil { @@ -31,6 +36,36 @@ func Init(opts *LoggerOptions) (func(), error) { } mw := io.MultiWriter(os.Stdout, f) log.SetOutput(mw) + + go func() { + for { + size, err := GetFileSize() + if err != nil { + panic(err) + } + if size >= maxSizeInBytes { + source, err := os.Open(logFilePath) + if err != nil { + panic(err) + } + destination, err := os.Create(logFilePath + "-" + time.Now().Format("20060102150405")) + if err != nil { + panic(err) + } + _, err = io.Copy(destination, source) + if err != nil { + panic(err) + } + source.Close() + destination.Close() + if err := os.Truncate(logFilePath, 0); err != nil { + panic(err) + } + } + time.Sleep(10 * time.Second) + } + }() + return func() { defer f.Close() }, nil @@ -98,3 +133,16 @@ func Error(s string) { str := color.RedString("%s", s) log.Print("[" + filename + ":" + fmt.Sprint(line) + "] " + str) } + +// GetFileSize returns the log file size +func GetFileSize() (int64, error) { + info, err := os.Stat(logFilePath) + if err != nil { + return 0, err + } + if !info.Mode().IsRegular() { + return 0, fmt.Errorf("%s is not a regular file", logFilePath) + } + bytes := info.Size() + return bytes, nil +} diff --git a/types.go b/types.go index 1f3eeee..7d77a2f 100644 --- a/types.go +++ b/types.go @@ -5,6 +5,7 @@ type LogLevel string // LoggerOptions to pass to the logger instance type LoggerOptions struct { - LogLevel LogLevel - LogFilePath string + LogLevel LogLevel + LogFilePath string + LogFileMaxSize int64 }