Skip to content

Instantly share code, notes, and snippets.

@apokalyptik apokalyptik/keep.go
Created Oct 6, 2015

What would you like to do?
package main
import (
var doTimeStamp = true
var doTee = true
var toFile = "/tmp/output.log"
var logFP *os.File
func init() {
flag.BoolVar(&doTimeStamp, "ts", doTimeStamp, "add timestamps to output")
flag.BoolVar(&doTee, "tee", doTee, "act like tee (echo input to stdout")
flag.StringVar(&toFile, "f", toFile, "filename to write")
func main() {
if _, err := os.Stat(toFile); err == nil {
var filename = toFile
for i := uint(0); i < ^uint(0); i++ {
filename = fmt.Sprintf("%s.%d", toFile, i)
if _, err := os.Stat(filename); os.IsNotExist(err) {
toFile = filename
if fp, err := os.Create(toFile); err != nil {
} else {
logFP = fp
fmt.Printf("Writing to %s\n\n", toFile)
var writeTo io.Writer
if doTee {
writeTo = io.MultiWriter(logFP, os.Stdout)
} else {
writeTo = logFP
if doTimeStamp {
log.SetFlags(log.Ldate | log.Lmicroseconds)
} else {
stdin := bufio.NewReader(os.Stdin)
for {
if line, err := stdin.ReadString('\n'); err == nil {
} else {
if line != "" {
if err != io.EOF {

This comment has been minimized.

Copy link
Owner Author

commented Oct 6, 2015

Usage of keep:
  -f string
        filename to write (default "/tmp/output.log")
        act like tee (echo input to stdout (default true)
        add timestamps to output (default true)

This little utility will redirect stdin to the specified file, /tmp/output.log by default. If that file exists it will write to /tmp/output.log.0, if that exists to /tmp/output.log.1, /tmp/output.log.2, and so on. That way you can reuse a single command and not accidentally lose previously logged data when you forget to change the filename on your redirects... By default it also prepends every line with a timestamp, such as 2015/10/06 16:43:27.355453 which is handy when trying to objectively tell whether something happened slower or faster on a given execution than in other logs, or other times in the same log...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.