Skip to content

Instantly share code, notes, and snippets.

@filevich
Created February 15, 2024 18:30
Show Gist options
  • Save filevich/8dc2581ceba00f49a46e98f4a025865b to your computer and use it in GitHub Desktop.
Save filevich/8dc2581ceba00f49a46e98f4a025865b to your computer and use it in GitHub Desktop.
go logrotate + verbose stdout example
package main
import (
"flag"
"fmt"
"io"
"log"
"os"
"strconv"
"github.com/natefinch/lumberjack/v3"
)
// flags
var (
logFilePtr = flag.String("log_file", "/tmp/mylog.log", "Path to the log file")
logSizePtr = flag.Int64("log_size", 500, "Max size of the log (in MiB)")
logBackupsPtr = flag.Int("log_backups", 5, "Max number of old log files to retain)")
verbosePtr = flag.Bool("verbose", false, "Should print to both the log file AND stdout?")
)
func init() {
flag.Parse()
}
func main() {
l, _ := lumberjack.NewRoller(
*logFilePtr,
(*logSizePtr)*1024*1024, // 500 megabytes
&lumberjack.Options{
MaxBackups: *logBackupsPtr,
LocalTime: true,
Compress: true,
})
ws := []io.Writer{l}
if *verbosePtr {
ws = append(ws, os.Stdout)
}
mw := io.MultiWriter(ws...)
log.SetOutput(l)
log.SetOutput(mw)
for i := 0; i < 100_000_000; i++ {
log.Println("hello world! #" + strconv.Itoa(i))
}
fmt.Println("done")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment