-
Notifications
You must be signed in to change notification settings - Fork 11
/
log.go
108 lines (97 loc) · 2.26 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package middleware
import (
"io"
std "log"
"strconv"
"sync"
"time"
"github.com/webx-top/echo"
)
type VisitorInfo struct {
RealIP string
Time time.Time
Elapsed time.Duration
Scheme string
Host string
URI string
Method string
UserAgent string
Referer string
RequestSize int64
ResponseSize int64
ResponseCode int
}
var emptyTime = time.Time{}
func (v *VisitorInfo) reset() {
v.RealIP = ``
v.Time = emptyTime
v.Elapsed = 0
v.Scheme = ``
v.Host = ``
v.URI = ``
v.Method = ``
v.UserAgent = ``
v.Referer = ``
v.RequestSize = 0
v.ResponseSize = 0
v.ResponseCode = 0
}
func (v *VisitorInfo) SetFromContext(c echo.Context) {
req := c.Request()
res := c.Response()
v.RealIP = c.RealIP()
v.UserAgent = req.UserAgent()
v.Referer = req.Referer()
v.RequestSize = req.Size()
v.Elapsed = time.Since(v.Time)
v.Method = req.Method()
v.Host = req.Host()
v.Scheme = req.Scheme()
v.URI = req.URI()
v.ResponseSize = res.Size()
v.ResponseCode = res.Status()
}
var DefaultLogWriter = GetDefaultLogWriter()
var visitorInfoPool = sync.Pool{
New: func() interface{} {
return &VisitorInfo{}
},
}
func Log(recv ...func(*VisitorInfo)) echo.MiddlewareFunc {
return LogWithWriter(nil, recv...)
}
func AcquireVisitorInfo() *VisitorInfo {
return visitorInfoPool.Get().(*VisitorInfo)
}
func ReleaseVisitorInfo(v *VisitorInfo) {
v.reset()
visitorInfoPool.Put(v)
}
func LogWithWriter(writer io.Writer, recv ...func(*VisitorInfo)) echo.MiddlewareFunc {
var logging func(*VisitorInfo)
if len(recv) > 0 {
logging = recv[0]
}
if writer == nil {
writer = DefaultLogWriter
}
logger := std.New(writer, ``, 0)
if logging == nil {
logging = func(v *VisitorInfo) {
logger.Println(":" + strconv.Itoa(v.ResponseCode) + ": " + v.Time.Format(time.RFC3339) + " " + v.RealIP + " " + v.Method + " " + v.Scheme + " " + v.Host + " " + v.URI + " " + v.Elapsed.String() + " " + strconv.FormatInt(v.ResponseSize, 10))
}
}
return func(h echo.Handler) echo.Handler {
return echo.HandlerFunc(func(c echo.Context) error {
info := AcquireVisitorInfo()
info.Time = time.Now()
if err := h.Handle(c); err != nil {
c.Error(err)
}
info.SetFromContext(c)
logging(info)
ReleaseVisitorInfo(info)
return nil
})
}
}