Blame view

logger/http_logs.go 1.4 KB
28a6cc60c   Marko Tikvić   Integrated logger...
1
  package logger
e2880d3fb   Marko Tikvić   integraded golloger
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
77
78
79
80
  
  import (
  	"bytes"
  	"fmt"
  	"net/http"
  	"net/http/httputil"
  	"os"
  	"strings"
  	"time"
  )
  
  const splitLine = "=============================================================="
  
  // 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()
  }
  
  // LogHTTPResponse ...
  func (l *Logger) LogHTTPResponse(data []byte, status int, startTime time.Time) string {
  	duration := time.Now().Sub(startTime)
  	jsonData, _ := printJSON(data)
  	return fmt.Sprintf("Response:
  %d %v %dB
  %s
  %s
  
  ", status, duration, len(data), jsonData, 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)
  }