-
Notifications
You must be signed in to change notification settings - Fork 0
/
log.go
100 lines (82 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
package accesslog
import (
"bytes"
"log"
"net/http"
"text/template"
"time"
"github.com/ericyaoxr/mcube/http/response"
"github.com/ericyaoxr/mcube/logger"
)
// LoggerEntry is the structure passed to the template.
type LoggerEntry struct {
StartTime string
Status int
Duration time.Duration
Hostname string
Method string
Path string
Request *http.Request
}
// LoggerDefaultFormat is the format logged used by the default Logger instance.
var LoggerDefaultFormat = "{{.Status}} | {{.Duration}} | {{.Hostname}} | {{.Method}} {{.Path}}"
// LoggerDefaultDateFormat is the format used for date by the default Logger instance.
var LoggerDefaultDateFormat = time.RFC3339
// Logger is a middleware handler that logs the request as it goes in and the response as it goes out.
type Logger struct {
log logger.StandardLogger
dateFormat string
template *template.Template
}
// New returns a new Logger instance
func New() *Logger {
lm := &Logger{dateFormat: LoggerDefaultDateFormat}
lm.SetFormat(LoggerDefaultFormat)
return lm
}
// NewWithLogger with logger
func NewWithLogger(log logger.StandardLogger) *Logger {
lm := &Logger{dateFormat: LoggerDefaultDateFormat, log: log}
lm.SetFormat(LoggerDefaultFormat)
return lm
}
// SetLogger 设置logger
func (l *Logger) SetLogger(log logger.StandardLogger) {
l.log = log
}
// SetFormat 设置日志输出格式的模板
func (l *Logger) SetFormat(format string) {
l.template = template.Must(template.New("negroni_parser").Parse(format))
}
// SetDateFormat 设置日志的时间格式
func (l *Logger) SetDateFormat(format string) {
l.dateFormat = format
}
// Handler 实现中间件
func (l *Logger) Handler(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(rw, r)
res := rw.(response.Response)
log := LoggerEntry{
StartTime: start.Format(l.dateFormat),
Status: res.Status(),
Duration: time.Since(start),
Hostname: r.Host,
Method: r.Method,
Path: r.URL.Path,
Request: r,
}
buff := &bytes.Buffer{}
l.template.Execute(buff, log)
l.debug(buff.String())
})
}
func (l *Logger) debug(msg string) {
if l.log != nil {
l.log.Debug(msg)
return
}
log.Print(msg)
return
}