/
log.go
72 lines (66 loc) · 1.92 KB
/
log.go
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
package http
import (
"bytes"
"encoding/json"
"math"
"strconv"
"time"
tp "github.com/henrylee2cn/teleport"
"github.com/henrylee2cn/teleport/plugin"
"github.com/henrylee2cn/teleport/utils"
)
var (
printDetail bool
countTime bool
slowCometDuration time.Duration = math.MaxInt64
)
func (r *requestHandler) runlog(startTime time.Time, label *plugin.ProxyLabel, seq string, inputBody []byte, outputBody *[]byte) {
var addr = r.ctx.RemoteAddr().String()
if label.RealIp != "" && label.RealIp != addr {
addr += "(real: " + label.RealIp + ")"
}
var (
costTimeStr string
printFunc = tp.Infof
)
if countTime {
costTime := time.Since(startTime)
costTimeStr = costTime.String()
if costTime >= slowCometDuration {
costTimeStr += "(slow)"
printFunc = tp.Warnf
}
} else {
costTimeStr = "-"
}
printFunc("PULL<- %s %s %s %q\nRECV(%s)\nSEND(%s)", addr, costTimeStr, label.Uri, seq, r.packetLogBytes(inputBody, r.ctx.Request.Header.Header(), false), r.packetLogBytes(*outputBody, r.ctx.Response.Header.Header(), r.errMsg != nil))
}
func (r *requestHandler) packetLogBytes(bodyBytes, headerBytes []byte, hasErr bool) []byte {
var size = len(bodyBytes) + len(headerBytes)
if hasErr {
size += len(r.errMsg)
}
var b = make([]byte, 0, 128)
b = append(b, '{')
b = append(b, '"', 's', 'i', 'z', 'e', '"', ':')
b = append(b, strconv.FormatUint(uint64(size), 10)...)
if hasErr {
b = append(b, ',', '"', 'e', 'r', 'r', 'o', 'r', '"', ':')
b = append(b, utils.ToJsonStr(r.errMsg, false)...)
}
if printDetail {
b = append(b, ',', '"', 'm', 'e', 't', 'a', '"', ':')
b = append(b, utils.ToJsonStr(headerBytes, false)...)
if !hasErr && len(bodyBytes) > 0 {
b = append(b, ',', '"', 'b', 'o', 'd', 'y', '"', ':')
b = append(b, utils.ToJsonStr(bodyBytes, false)...)
}
}
b = append(b, '}')
buf := bytes.NewBuffer(nil)
err := json.Indent(buf, b, "", " ")
if err != nil {
return b
}
return buf.Bytes()
}