In Go, you can configure log rotation based on time intervals using the log
package along with the gopkg.in/natefinch/lumberjack.v2
package. Here's an example:
lumberjack.v2
package using the following command:go get gopkg.in/natefinch/lumberjack.v2
package main
import (
"log"
"os"
"time"
"gopkg.in/natefinch/lumberjack.v2"
)
func configureLogRotation() {
maxSize := 10 // megabytes
maxBackups := 5
maxAge := 7 // days
log.SetOutput(&lumberjack.Logger{
Filename: "logfile.log",
MaxSize: maxSize,
MaxBackups: maxBackups,
MaxAge: maxAge,
LocalTime: true,
})
// Rotate logs every hour
go func() {
for {
time.Sleep(time.Hour)
log.Println("Rotating log due to time interval")
log.SetOutput(&lumberjack.Logger{
Filename: "logfile.log",
MaxSize: maxSize,
MaxBackups: maxBackups,
MaxAge: maxAge,
LocalTime: true,
})
}
}()
}
configureLogRotation()
function at the beginning of your Go program to set up log rotation based on time intervals:func main() {
configureLogRotation()
// Rest of your program
}
This code will create a log file named "logfile.log" and automatically rotate the log file every hour. The rotated log files will be named "logfile.log.1", "logfile.log.2", and so on, up to maxBackups
. The old log files older than maxAge
days will be removed.
Make sure to adjust the values of maxSize
, maxBackups
, and maxAge
as per your requirements.