From 15d3e5d0508577dd65f681d0354411223116d979 Mon Sep 17 00:00:00 2001 From: Dingjun Date: Fri, 8 Sep 2017 16:32:39 +0800 Subject: [PATCH] add log for per request --- routers.go | 34 ++++++++++++++++++++++++++++++++-- server.go | 3 +++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/routers.go b/routers.go index ac10b4e..1f75f06 100644 --- a/routers.go +++ b/routers.go @@ -5,7 +5,9 @@ import ( "fmt" auth "github.com/fangdingjun/go-http-auth" "github.com/fangdingjun/gofast" + loghandler "github.com/gorilla/handlers" "github.com/gorilla/mux" + "io" "log" "net" "net/http" @@ -13,12 +15,37 @@ import ( "net/url" "os" "regexp" + "sync" //"path/filepath" "strings" ) +type logwriter struct { + w io.Writer + l *sync.Mutex +} + +func (lw *logwriter) Write(buf []byte) (int, error) { + lw.l.Lock() + defer lw.l.Unlock() + return lw.w.Write(buf) +} + func initRouters(cfg conf) { + logout := os.Stdout + + if logfile != "" { + fp, err := os.OpenFile(logfile, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644) + if err != nil { + log.Println(err) + } else { + logout = fp + } + } + + w := &logwriter{logout, new(sync.Mutex)} + for _, l := range cfg { router := mux.NewRouter() domains := []string{} @@ -110,7 +137,7 @@ func initRouters(cfg conf) { srv := http.Server{ Addr: addr, TLSConfig: tlsconfig, - Handler: hdlr, + Handler: loghandler.CombinedLoggingHandler(w, hdlr), } log.Printf("listen https on %s", addr) if err := srv.ListenAndServeTLS("", ""); err != nil { @@ -119,7 +146,10 @@ func initRouters(cfg conf) { } else { log.Printf("listen http on %s", addr) - if err := http.ListenAndServe(addr, hdlr); err != nil { + if err := http.ListenAndServe( + addr, + loghandler.CombinedLoggingHandler(w, hdlr), + ); err != nil { log.Fatal(err) } } diff --git a/server.go b/server.go index 13f4c5a..40c5bf2 100644 --- a/server.go +++ b/server.go @@ -7,9 +7,12 @@ import ( //"net/http" ) +var logfile string + func main() { var configfile string flag.StringVar(&configfile, "c", "config.yaml", "config file") + flag.StringVar(&logfile, "log", "", "log file") flag.Parse() c, err := loadConfig(configfile) if err != nil {