From cccb4b47c00c510cb8071d3619b343b8fdeb9527 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marko=20Tikvi=C4=87?= Date: Wed, 9 May 2018 00:37:22 +0200 Subject: [PATCH] log http response --- main.go | 40 +++++++++++++++++++++++++++------------- 1 file changed, 27 insertions(+), 13 deletions(-) diff --git a/main.go b/main.go index cefcd94..afabc17 100644 --- a/main.go +++ b/main.go @@ -2,8 +2,8 @@ package gologger import ( "fmt" - "io/ioutil" "net/http" + "net/http/httputil" "os" "path/filepath" "runtime" @@ -84,26 +84,40 @@ func (l *Logger) LogRequest(req *http.Request, userid string) { } var b strings.Builder + b.WriteString("Request:\n") // CLF-like header ts := time.Now().Format(time.RFC3339) - fmt.Fprintf(&b, "%s - %s [%s] \"%s %s\" %s\n", req.RemoteAddr, userid, ts, req.Method, req.URL.Path, req.Proto) + fmt.Fprintf(&b, "%s %s\n", req.RemoteAddr, ts) - b.WriteString("\nURL encoded:\n") - for k, v := range req.Form { - fmt.Fprintf(&b, "%s = %s\n", k, v) - } - - b.WriteString("\nBody:\n") - buf, err := ioutil.ReadAll(req.Body) - if err == nil { - b.WriteString(string(buf)) - } else { + body, err := httputil.DumpRequest(req, true) + if err != nil { fmt.Fprintf(os.Stderr, "%v\n", err) + } else { + b.WriteString(string(body)) } b.WriteString("\n\n") msg := b.String() - //fmt.Println(msg) + + l.mu.Lock() + defer l.mu.Unlock() + + if l.shouldSplit(len(msg)) { + l.split() + } + l.outputFile.WriteString(msg) + } +} + +func (l *Logger) LogResponse(w http.ResponseWriter, duration time.Duration) { + if l.outputFile != nil { + var b strings.Builder + b.WriteString("Response:\n") + for k, v := range w.Header() { + b.WriteString(fmt.Sprintf("%s: %s\n", k, v)) + } + b.WriteString(fmt.Sprintf("\nCompleted in: %v\n", duration)) + msg := b.String() l.mu.Lock() defer l.mu.Unlock() -- 1.8.1.2