Skip to content

Commit

Permalink
Enable log rotation
Browse files Browse the repository at this point in the history
  • Loading branch information
pravinba9495 committed May 19, 2022
1 parent e62469f commit 1c2fe80
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 2 deletions.
48 changes: 48 additions & 0 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@ import (
"log"
"os"
"runtime"
"time"

"github.com/fatih/color"
)

var (
currentLogLevel LogLevel = LevelError
logFilePath string = "logfile.txt"
maxSizeInBytes int64 = 5 * 1024 * 1024
)

// Init initializes a logger
Expand All @@ -24,13 +26,46 @@ 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 {
return func() {}, err
}
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
Expand Down Expand Up @@ -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
}
5 changes: 3 additions & 2 deletions types.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

0 comments on commit 1c2fe80

Please sign in to comment.