Debian Codegraph @

server/requestlog/requestlog.go

raw
1 // Copyright 2018 The Go Cloud Development Kit Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Package requestlog provides an http.Handler that logs information
16 // about requests.
17 package requestlog // import "gocloud.dev/server/requestlog"
18
19 import (
20 "bufio"
21 "errors"
22 "io"
23 "net"
24 "net/http"
25 "strconv"
26 "time"
27
28 "go.opentelemetry.io/otel/trace"
29 )
30
31 // Logger wraps the Log method. Log must be safe to call from multiple
32 // goroutines. Log must not hold onto an Entry after it returns.
33 type Logger interface {
34 Log(*Entry)
35 }
36
37 // A Handler emits request information to a Logger.
38 type Handler struct {
39 log Logger
40 h http.Handler
41 }
42
43 // NewHandler returns a handler that emits information to log and calls
44 // h.ServeHTTP.
45 func NewHandler(log Logger, h http.Handler) *Handler {
46 return &Handler{
47 log: log,
48 h: h,
49 }
50 }
51
52 // ServeHTTP calls its underlying handler's ServeHTTP method, then calls
53 // Log after the handler returns.
54 func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
55 start := time.Now()
56 span := trace.SpanFromContext(r.Context())
57 sc := span.SpanContext()
58 ent := &Entry{
59 Request: cloneRequestWithoutBody(r),
60 ReceivedTime: start,
61 RequestMethod: r.Method,
62 RequestURL: r.URL.String(),
63 RequestHeaderSize: headerSize(r.Header),
64 UserAgent: r.UserAgent(),
65 Referer: r.Referer(),
66 Proto: r.Proto,
67 RemoteIP: ipFromHostPort(r.RemoteAddr),
68 TraceID: sc.TraceID(),
69 SpanID: sc.SpanID(),
70 }
71 if addr, ok := r.Context().Value(http.LocalAddrContextKey).(net.Addr); ok {
72 ent.ServerIP = ipFromHostPort(addr.String())
73 }
74 r2 := new(http.Request)
75 *r2 = *r
76 rcc := &readCounterCloser{r: r.Body}
77 r2.Body = rcc
78 w2 := &responseStats{w: w}
79
80 h.h.ServeHTTP(w2, r2)
81
82 ent.Latency = time.Since(start)
83 // The handler may or may not have read the entire body. If the request
84 // includes a Content-Length header, use that for a more accurate
85 // RequestBodySize.
86 ent.RequestBodySize = rcc.n
87 if contentLengthStr := r.Header.Get("Content-Length"); contentLengthStr != "" {
88 ent.RequestBodySize, _ = strconv.ParseInt(contentLengthStr, 10, 64)
89 }
90 ent.Status = w2.code
91 if ent.Status == 0 {
92 ent.Status = http.StatusOK
93 }
94 ent.ResponseHeaderSize, ent.ResponseBodySize = w2.size()
95 h.log.Log(ent)
96 }
97
98 func cloneRequestWithoutBody(r *http.Request) *http.Request {
99 r = r.Clone(r.Context())
100 r.Body = nil
101 return r
102 }
103
104 // Entry records information about a completed HTTP request.
105 type Entry struct {
106 // Request is the http request that has been completed.
107 //
108 // This request's Body is always nil, regardless of the actual request body.
109 Request *http.Request
110
111 ReceivedTime time.Time
112 RequestBodySize int64
113
114 Status int
115 ResponseHeaderSize int64
116 ResponseBodySize int64
117 Latency time.Duration
118 TraceID trace.TraceID
119 SpanID trace.SpanID
120
121 // Deprecated. This value is available by evaluating Request.Referer().
122 Referer string
123 // Deprecated. This value is available directing in Request.Proto.
124 Proto string
125 // Deprecated. This value is available directly in Request.Method.
126 RequestMethod string
127 // Deprecated. This value is available directly in Request.URL.
128 RequestURL string
129 // Deprecated. This value is available by evaluating Request.Header.
130 RequestHeaderSize int64
131 // Deprecated. This value is available by evaluating Request.Header.
132 UserAgent string
133 // Deprecated. This value is available by evaluating Request.RemoteAddr..
134 RemoteIP string
135 // Deprecated. This value is available by evaluating reading the
136 // http.LocalAddrContextKey value from the context returned by Request.Context().
137 ServerIP string
138 }
139
140 func ipFromHostPort(hp string) string {
141 h, _, err := net.SplitHostPort(hp)
142 if err != nil {
143 return ""
144 }
145 if len(h) > 0 && h[0] == '[' {
146 return h[1 : len(h)-1]
147 }
148 return h
149 }
150
151 type readCounterCloser struct {
152 r io.ReadCloser
153 n int64
154 err error
155 }
156
157 func (rcc *readCounterCloser) Read(p []byte) (n int, err error) {
158 if rcc.err != nil {
159 return 0, rcc.err
160 }
161 n, rcc.err = rcc.r.Read(p)
162 rcc.n += int64(n)
163 return n, rcc.err
164 }
165
166 func (rcc *readCounterCloser) Close() error {
167 rcc.err = errors.New("read from closed reader")
168 return rcc.r.Close()
169 }
170
171 type writeCounter int64
172
173 func (wc *writeCounter) Write(p []byte) (n int, err error) {
174 *wc += writeCounter(len(p))
175 return len(p), nil
176 }
177
178 func headerSize(h http.Header) int64 {
179 var wc writeCounter
180 _ = h.Write(&wc)
181 return int64(wc) + 2 // for CRLF
182 }
183
184 type responseStats struct {
185 w http.ResponseWriter
186 hsize int64
187 wc writeCounter
188 code int
189 hijacked bool
190 }
191
192 func (r *responseStats) Header() http.Header {
193 return r.w.Header()
194 }
195
196 func (r *responseStats) WriteHeader(statusCode int) {
197 if r.code != 0 {
198 return
199 }
200 r.hsize = headerSize(r.w.Header())
201 r.w.WriteHeader(statusCode)
202 r.code = statusCode
203 }
204
205 func (r *responseStats) Write(p []byte) (n int, err error) {
206 if r.code == 0 {
207 r.WriteHeader(http.StatusOK)
208 }
209 n, err = r.w.Write(p)
210 _, _ = r.wc.Write(p[:n])
211 return
212 }
213
214 func (r *responseStats) size() (hdr, body int64) {
215 if r.code == 0 {
216 return headerSize(r.w.Header()), 0
217 }
218 // Use the header size from the time WriteHeader was called.
219 // The Header map can be mutated after the call to add HTTP Trailers,
220 // which we don't want to count.
221 return r.hsize, int64(r.wc)
222 }
223
224 func (r *responseStats) Hijack() (_ net.Conn, _ *bufio.ReadWriter, err error) {
225 defer func() {
226 if err == nil {
227 r.hijacked = true
228 }
229 }()
230 if hj, ok := r.w.(http.Hijacker); ok {
231 return hj.Hijack()
232 }
233 return nil, nil, errors.New("underlying ResponseWriter does not support hijacking")
234 }
235
236 func (r *responseStats) Flush() {
237 if fl, ok := r.w.(http.Flusher); ok {
238 fl.Flush()
239 }
240 }