Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@apokalyptik
Created October 6, 2015 16:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apokalyptik/d51defb9413870a47902 to your computer and use it in GitHub Desktop.
Save apokalyptik/d51defb9413870a47902 to your computer and use it in GitHub Desktop.
package main
import (
"bufio"
"flag"
"fmt"
"io"
"log"
"os"
)
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() {
flag.Parse()
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
break
}
}
}
if fp, err := os.Create(toFile); err != nil {
log.Fatal(err)
} 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
}
log.SetOutput(writeTo)
if doTimeStamp {
log.SetFlags(log.Ldate | log.Lmicroseconds)
} else {
log.SetFlags(0)
}
stdin := bufio.NewReader(os.Stdin)
for {
if line, err := stdin.ReadString('\n'); err == nil {
log.Print(line)
} else {
if line != "" {
log.Print(line)
}
if err != io.EOF {
log.SetOutput(os.Stderr)
log.Fatal(err)
}
return
}
}
}
@apokalyptik
Copy link
Author

Usage of keep:
  -f string
        filename to write (default "/tmp/output.log")
  -tee
        act like tee (echo input to stdout (default true)
  -ts
        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