Commit cccb4b47c00c510cb8071d3619b343b8fdeb9527

Authored by Marko Tikvić
1 parent df74f4a7ee
Exists in master

log http response

Showing 1 changed file with 27 additions and 13 deletions   Show diff stats
... ... @@ -2,8 +2,8 @@ package gologger
2 2  
3 3 import (
4 4 "fmt"
5   - "io/ioutil"
6 5 "net/http"
  6 + "net/http/httputil"
7 7 "os"
8 8 "path/filepath"
9 9 "runtime"
... ... @@ -84,26 +84,40 @@ func (l *Logger) LogRequest(req *http.Request, userid string) {
84 84 }
85 85  
86 86 var b strings.Builder
  87 + b.WriteString("Request:\n")
87 88 // CLF-like header
88 89 ts := time.Now().Format(time.RFC3339)
89   - fmt.Fprintf(&b, "%s - %s [%s] \"%s %s\" %s\n", req.RemoteAddr, userid, ts, req.Method, req.URL.Path, req.Proto)
  90 + fmt.Fprintf(&b, "%s %s\n", req.RemoteAddr, ts)
90 91  
91   - b.WriteString("\nURL encoded:\n")
92   - for k, v := range req.Form {
93   - fmt.Fprintf(&b, "%s = %s\n", k, v)
94   - }
95   -
96   - b.WriteString("\nBody:\n")
97   - buf, err := ioutil.ReadAll(req.Body)
98   - if err == nil {
99   - b.WriteString(string(buf))
100   - } else {
  92 + body, err := httputil.DumpRequest(req, true)
  93 + if err != nil {
101 94 fmt.Fprintf(os.Stderr, "%v\n", err)
  95 + } else {
  96 + b.WriteString(string(body))
102 97 }
103 98 b.WriteString("\n\n")
104 99  
105 100 msg := b.String()
106   - //fmt.Println(msg)
  101 +
  102 + l.mu.Lock()
  103 + defer l.mu.Unlock()
  104 +
  105 + if l.shouldSplit(len(msg)) {
  106 + l.split()
  107 + }
  108 + l.outputFile.WriteString(msg)
  109 + }
  110 +}
  111 +
  112 +func (l *Logger) LogResponse(w http.ResponseWriter, duration time.Duration) {
  113 + if l.outputFile != nil {
  114 + var b strings.Builder
  115 + b.WriteString("Response:\n")
  116 + for k, v := range w.Header() {
  117 + b.WriteString(fmt.Sprintf("%s: %s\n", k, v))
  118 + }
  119 + b.WriteString(fmt.Sprintf("\nCompleted in: %v\n", duration))
  120 + msg := b.String()
107 121  
108 122 l.mu.Lock()
109 123 defer l.mu.Unlock()
... ...