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