Blame view

http_logs.go 1.32 KB
829723543   Marko Tikvić   Improved tracing....
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
  package gologger
  
  import (
  	"bytes"
  	"fmt"
  	"net/http"
  	"net/http/httputil"
  	"os"
  	"strings"
  	"time"
  )
  
  // LogHTTPRequest ...
  func (l *Logger) LogHTTPRequest(req *http.Request, userID string) string {
  	if userID == "" {
  		userID = "-"
  	}
  
  	var b strings.Builder
  
  	b.WriteString("Request:
  ")
  	// CLF-like header
  	fmt.Fprintf(&b, "%s %s %s
  ", req.RemoteAddr, userID, time.Now().Format(dateTimeFormat))
  
  	body, err := httputil.DumpRequest(req, true)
  	if err != nil {
  		fmt.Fprintf(os.Stderr, "%v
  ", err)
  	}
  
  	const sepStr = "\r
  \r
  "
  	sepIndex := bytes.Index(body, []byte(sepStr))
  	if sepIndex == -1 {
  		b.WriteString(string(body) + "
  
  ")
  	} else {
  		sepIndex += len(sepStr)
  		payload, _ := printJSON(body[sepIndex:])
  		b.WriteString(string(body[:sepIndex]) + string(payload) + "
  
  ")
  	}
  
  	return b.String()
  }
  
  const splitLine = "=============================================================="
  
  // LogHTTPResponse ...
  func (l *Logger) LogHTTPResponse(status int, duration time.Duration, size int) string {
  	return fmt.Sprintf("Response:
  %d %v %dB
  %s
  ", status, duration, size, splitLine)
  }
  
  // CombineHTTPLogs ...
  func (l *Logger) CombineHTTPLogs(in string, out string) {
  	if l.outputFile == nil {
  		return
  	}
  
  	l.mu.Lock()
  	defer l.mu.Unlock()
  
  	msg := in + out
  	if l.shouldSplit(len(msg)) {
  		l.split()
  	}
  	l.outputFile.WriteString(msg)
  }