http_logs.go
1.32 KB
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
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:\n")
// CLF-like header
fmt.Fprintf(&b, "%s %s %s\n", req.RemoteAddr, userID, time.Now().Format(dateTimeFormat))
body, err := httputil.DumpRequest(req, true)
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
}
const sepStr = "\r\n\r\n"
sepIndex := bytes.Index(body, []byte(sepStr))
if sepIndex == -1 {
b.WriteString(string(body) + "\n\n")
} else {
sepIndex += len(sepStr)
payload, _ := printJSON(body[sepIndex:])
b.WriteString(string(body[:sepIndex]) + string(payload) + "\n\n")
}
return b.String()
}
const splitLine = "##############################################################"
// LogHTTPResponse ...
func (l *Logger) LogHTTPResponse(status int, duration time.Duration, size int) string {
return fmt.Sprintf("Response:\n%d %v %dB\n%s\n", 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)
}