Although @Crast gave a very good answer, I also want to draw attention to this - logger Nate Finch , which I eventually used.
Here's how to use it:
- First, clone the lumberjack's storage OR somehow get it.
- Run the
go install command for the folder. - Now import go "log" package and "lumberjack package".
Import ("magazine" "Github.com/natefinch/lumberjack")
- Now use it in your code like this:
Outside of main, declare a log variable.
var errLog *log.Logger
Inside the 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,
Now, as soon as the file size is 1 MB, a new file is created to save previous logs with current timestamps, and new logs will continue to be logged in the foo.log file. In addition, I created the file using os.OpenFile, but you may not need it, since this is done internally by the lumberjack, but I preferred it that way. Thanks, hope this helps. Thanks again @Crast and NateFinch .
source share