How to configure log rotation based on time intervals in Go?

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:

  1. First, install the lumberjack.v2 package using the following command:
go get gopkg.in/natefinch/lumberjack.v2
  1. Import the required packages in your Go file:
package main import ( "log" "os" "time" "gopkg.in/natefinch/lumberjack.v2" )
  1. Configure log rotation based on time intervals. You can set the maximum size of each log file, maximum number of old log files to retain, and the time interval at which file rotation occurs:
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, }) } }() }
  1. Finally, call the 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.