Though @Crast has given a very good answer, I want to also bring to the notice - lumberjack logger by Nate Finch which I ended up using.
Here is how to use it:
- First, clone the lumberjack repository OR get it somehow.
- Run the
go install
command on the folder.
- Now import go's "log" package and "lumberjack package".
import (
"log"
"github.com/natefinch/lumberjack"
)
- Now use it in your code like this:
Outside of main, declare your log variable.
var errLog *log.Logger
Inside main:
e, err := os.OpenFile("./foo.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
fmt.Printf("error opening file: %v", err)
os.Exit(1)
}
errLog = log.New(e, "", log.Ldate|log.Ltime)
errLog.SetOutput(&lumberjack.Logger{
Filename: "./foo.log",
MaxSize: 1, // megabytes after which new file is created
MaxBackups: 3, // number of backups
MaxAge: 28, //days
})
Now as soon as the file size get 1MB, a new file is created to keep the previous logs with the current timestamps, and the new logs will continue to log into foo.log file. Also, I have created the file using os.OpenFile but you may not need it as lumberjack internally does it, but I preferred it that way. Thanks, hope it helps.
Once again thanks to @Crast and NateFinch.
log
package vialog.SetOutput
and handles log rotation, max sizes and retaining backups.