1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
|
package main
/* Similar to previous example but uses a BufferedFileWriter
* When buf is full OR every 30 seconds, the buffer is flushed to disk
*
* care is done to make sure transient or partial log messages are not written.
*
* Note the signal handler catches SIGTERM to flush out and existing buffers
*/
import (
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"github.com/client9/reopen"
)
func main() {
f, err := reopen.NewFileWriter("/tmp/example.log")
if err != nil {
log.Fatalf("Unable to set output log: %s", err)
}
bf := reopen.NewBufferedFileWriter(f)
log.SetOutput(bf)
sighup := make(chan os.Signal, 2)
signal.Notify(sighup, syscall.SIGHUP, syscall.SIGTERM)
go func() {
for {
s := <-sighup
switch s {
case syscall.SIGHUP:
fmt.Printf("Got a sighup\n")
bf.Reopen()
case syscall.SIGTERM:
fmt.Printf("Got SIGTERM\n")
// make sure any remaining logs are flushed out
bf.Close()
os.Exit(0)
}
}
}()
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s", r.URL.Path)
fmt.Fprintf(w, "%s\n", r.URL.Path)
})
log.Fatal(http.ListenAndServe("127.0.0.1:8123", nil))
}
|