/
logging.go
179 lines (153 loc) · 4.26 KB
/
logging.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
package logging
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"runtime/debug"
"strings"
"time"
"github.com/pkg/errors"
)
var MaxFormPrefix = 256
func SetMaxFormPrefix(i int) {
MaxFormPrefix = i
}
func FormPrefix(form url.Values) string {
var buf strings.Builder
// appendBuf will append s to buf until it is "filled" (based on MaxFormPrefix)
appendBuf := func(s string) bool {
if buf.Len()+len(s) >= MaxFormPrefix {
remaining := MaxFormPrefix - buf.Len()
if remaining > 0 {
buf.WriteString(s[:remaining])
}
return false
}
buf.WriteString(s)
return true
}
for k, values := range form {
keyEscaped := url.QueryEscape(k)
for _, v := range values {
if buf.Len() >= MaxFormPrefix {
return buf.String()
}
if buf.Len() > 0 {
buf.WriteByte('&')
}
if !appendBuf(keyEscaped) {
return buf.String()
}
buf.WriteByte('=')
if buf.Len()+len(v) >= MaxFormPrefix {
remaining := MaxFormPrefix - buf.Len()
if remaining > 0 {
if !appendBuf(url.QueryEscape(v[:remaining])) {
return buf.String()
}
}
} else {
if !appendBuf(url.QueryEscape(v)) {
return buf.String()
}
}
}
}
return buf.String()
}
const ApacheFormatPattern = "%s - - [%s] \"%s %d %d\" %f %s\n"
type ApacheLogRecord struct {
http.ResponseWriter `json:"-"`
IP string `json:"remoteAddr,omitempty"`
Time time.Time `json:"time,omitempty"`
Method string `json:"method,omitempty"`
URI string `json:"path,omitempty"`
Protocol string `json:"protocol,omitempty"`
Status int `json:"status,omitempty"`
ResponseBytes int64 `json:"responseBytes,omitempty"`
ElapsedTime float64 `json:"duration,omitempty"`
FormPrefix string `json:"query,omitempty"`
}
func (r *ApacheLogRecord) Log(out io.Writer) {
timeFormatted := r.Time.Format("02/Jan/2006 15:04:05")
requestLine := fmt.Sprintf("%s %s %s", r.Method, r.URI, r.Protocol)
fmt.Fprintf(out, ApacheFormatPattern, r.IP, timeFormatted, requestLine, r.Status, r.ResponseBytes,
r.ElapsedTime, r.FormPrefix)
}
func (r *ApacheLogRecord) LogJson(out io.Writer) {
data, err := json.Marshal(r)
if err == nil {
out.Write(append(data, byte(10)))
}
}
func (r *ApacheLogRecord) Write(p []byte) (int, error) {
written, err := r.ResponseWriter.Write(p)
r.ResponseBytes += int64(written)
return written, err
}
func (r *ApacheLogRecord) WriteHeader(status int) {
r.Status = status
r.ResponseWriter.WriteHeader(status)
}
type LogRecordHandler func(*ApacheLogRecord)
func LogToWriter(out io.Writer) LogRecordHandler {
return func(l *ApacheLogRecord) {
l.Log(out)
}
}
func LogJsonToWriter(out io.Writer) LogRecordHandler {
return func(l *ApacheLogRecord) {
l.LogJson(out)
}
}
type ApacheLoggingHandler struct {
handler http.Handler
logHandlers []LogRecordHandler
}
func NewApacheLoggingHandler(handler http.Handler, logHandlers ...LogRecordHandler) http.Handler {
return &ApacheLoggingHandler{
handler: handler,
logHandlers: logHandlers,
}
}
func (h *ApacheLoggingHandler) runHandler(rw http.ResponseWriter, r *http.Request) (err error) {
defer func() {
if rec := recover(); rec != nil {
// Just return a stack trace always
err = errors.Wrap(fmt.Errorf(string(debug.Stack())), "Error running handler")
}
}()
h.handler.ServeHTTP(rw, r)
return
}
func (h *ApacheLoggingHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
clientIP := r.RemoteAddr
if colon := strings.LastIndex(clientIP, ":"); colon != -1 {
clientIP = clientIP[:colon]
}
r.ParseForm()
record := &ApacheLogRecord{
ResponseWriter: rw,
IP: clientIP,
Method: r.Method,
URI: r.URL.Path,
Protocol: r.Proto,
Status: http.StatusOK,
FormPrefix: FormPrefix(r.Form),
}
startTime := time.Now()
if err := h.runHandler(record, r); err != nil {
// If we have an error we want to clear any Content-Encoding that may have been set
// as we are just going to write direct
rw.Header().Del("Content-Encoding")
http.Error(record, err.Error(), http.StatusInternalServerError)
}
finishTime := time.Now()
record.Time = finishTime.UTC()
record.ElapsedTime = finishTime.Sub(startTime).Seconds()
for _, logHandler := range h.logHandlers {
logHandler(record)
}
}