This repository has been archived by the owner on Oct 25, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.go
91 lines (76 loc) · 2.15 KB
/
logger.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
package gomiddleware
import (
"bytes"
"io"
"log"
"net/http"
"os"
"text/template"
"time"
)
// LogEntry is the structure
// passed to the template.
type LogEntry struct {
StartTime string
Status int
Duration time.Duration
Hostname string
Method string
Path string
}
// LogDefaultFormat is the format
// logged used by the default Log instance.
var LogDefaultFormat = "{{.StartTime}} | {{.Status}} | \t {{.Duration}} | {{.Hostname}} | {{.Method}} {{.Path}} \n"
// LogDefaultDateFormat is the
// format used for date by the
// default Log instance.
var LogDefaultDateFormat = time.RFC3339
// ALogger interface
type ALogger interface {
Println(v ...interface{})
Printf(format string, v ...interface{})
}
// Log is a middleware handler that logs the request as it goes in and the response as it goes out.
type Logger struct {
// LoggerInterface implements more log.Logger interface to be compatible with other implementations
ALogger
dateFormat string
template *template.Template
}
// NewLogger returns a new Logger instance
func NewLogger() *Logger {
logger := &Logger{ALogger: log.New(os.Stdout, "[negroni] ", 0), dateFormat: LogDefaultDateFormat}
logger.SetFormat(LogDefaultFormat)
return logger
}
// NewLogger with io.writer returns a new Logger instance
func NewLoggerWithStream(w io.Writer) *Logger {
if w == nil {
w = os.Stdout
}
logger := &Logger{ALogger: log.New(w, "[negroni] ", 0), dateFormat: LogDefaultDateFormat}
logger.SetFormat(LogDefaultFormat)
return logger
}
func (l *Logger) SetFormat(format string) {
l.template = template.Must(template.New("negroni_parser").Parse(format))
}
func (l *Logger) SetDateFormat(format string) {
l.dateFormat = format
}
func (l *Logger) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
start := time.Now()
next(rw, r)
res := rw.(ResponseWriter)
log := LogEntry{
StartTime: start.Format(l.dateFormat),
Status: res.Status(),
Duration: time.Since(start),
Hostname: r.Host,
Method: r.Method,
Path: r.URL.Path,
}
buff := &bytes.Buffer{}
l.template.Execute(buff, log)
l.Printf(buff.String())
}