tsweb: extra logging fields for HTTP handlers

Signed-off-by: David Crawshaw <[email protected]>
This commit is contained in:
David Crawshaw committed 2020-07-13 11:56:06 +10:00
1 parent 977381f9cc
commit d7ffecdfc9
2 files changed
+20

No files matched your search

+6
View File
@@ -46,6 +46,12 @@ type AccessLogRecord struct {
Bytes int `json:"bytes"`
// Error encountered during request processing.
Err string `json:"err"`
// Extra contains extra fields logged by the HTTP handler.
//
// It is called "x" in the JSON both for brevity and so
// it comes last.
Extra map[string]string `json:"x,omitempty"`
}
// String returns m as a JSON string.
+14
View File
@@ -222,6 +222,7 @@ func (h retHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
msg.Seconds = h.timeNow().Sub(msg.When).Seconds()
msg.Code = lw.code
msg.Bytes = lw.bytes
msg.Extra = lw.extra
switch {
case lw.hijacked:
@@ -264,6 +265,18 @@ func (h retHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
}
// Log adds name/value to the logs from a StdHandler ResponseWriter.
func Log(w http.ResponseWriter, name, value string) {
lw, _ := w.(*loggingResponseWriter)
if lw == nil {
return
}
if lw.extra == nil {
lw.extra = make(map[string]string)
}
lw.extra[name] = value
}
// loggingResponseWriter wraps a ResponseWriter and record the HTTP
// response code that gets sent, if any.
type loggingResponseWriter struct {
@@ -272,6 +285,7 @@ type loggingResponseWriter struct {
bytes int
hijacked bool
logf logger.Logf
extra map[string]string // extra logging fields
}
// WriteHeader implements http.Handler.