Created
February 15, 2024 18:30
-
-
Save filevich/8dc2581ceba00f49a46e98f4a025865b to your computer and use it in GitHub Desktop.
go logrotate + verbose stdout example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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