git.iko.soy/typeable/oauth2-proxy
on v3.0.0 help sign in
typeable/oauth2-proxy/logging_handler.go
168 lines 4.5 kB history raw
1// largely adapted from https://github.com/gorilla/handlers/blob/master/handlers.go
2// to add logging of request duration as last value (and drop referrer)
4package main
6import (
7 "fmt"
8 "io"
9 "net"
10 "net/http"
11 "net/url"
12 "text/template"
13 "time"
16const (
17 defaultRequestLoggingFormat = "{{.Client}} - {{.Username}} [{{.Timestamp}}] {{.Host}} {{.RequestMethod}} {{.Upstream}} {{.RequestURI}} {{.Protocol}} {{.UserAgent}} {{.StatusCode}} {{.ResponseSize}} {{.RequestDuration}}"
20// responseLogger is wrapper of http.ResponseWriter that keeps track of its HTTP status
21// code and body size
22type responseLogger struct {
23 w http.ResponseWriter
24 status int
25 size int
26 upstream string
27 authInfo string
30// Header returns the ResponseWriter's Header
31func (l *responseLogger) Header() http.Header {
32 return l.w.Header()
35// ExtractGAPMetadata extracts and removes GAP headers from the ResponseWriter's
36// Header
37func (l *responseLogger) ExtractGAPMetadata() {
38 upstream := l.w.Header().Get("GAP-Upstream-Address")
39 if upstream != "" {
40 l.upstream = upstream
41 l.w.Header().Del("GAP-Upstream-Address")
42 }
43 authInfo := l.w.Header().Get("GAP-Auth")
44 if authInfo != "" {
45 l.authInfo = authInfo
46 l.w.Header().Del("GAP-Auth")
47 }
50// Write writes the response using the ResponseWriter
51func (l *responseLogger) Write(b []byte) (int, error) {
52 if l.status == 0 {
53 // The status will be StatusOK if WriteHeader has not been called yet
54 l.status = http.StatusOK
55 }
56 l.ExtractGAPMetadata()
57 size, err := l.w.Write(b)
58 l.size += size
59 return size, err
62// WriteHeader writes the status code for the Response
63func (l *responseLogger) WriteHeader(s int) {
64 l.ExtractGAPMetadata()
65 l.w.WriteHeader(s)
66 l.status = s
69// Status returns the response status code
70func (l *responseLogger) Status() int {
71 return l.status
74// Size returns teh response size
75func (l *responseLogger) Size() int {
76 return l.size
79// logMessageData is the container for all values that are available as variables in the request logging format.
80// All values are pre-formatted strings so it is easy to use them in the format string.
81type logMessageData struct {
82 Client,
83 Host,
84 Protocol,
85 RequestDuration,
86 RequestMethod,
87 RequestURI,
88 ResponseSize,
89 StatusCode,
90 Timestamp,
91 Upstream,
92 UserAgent,
93 Username string
96// loggingHandler is the http.Handler implementation for LoggingHandlerTo and its friends
97type loggingHandler struct {
98 writer io.Writer
99 handler http.Handler
100 enabled bool
101 logTemplate *template.Template
104// LoggingHandler provides an http.Handler which logs requests to the HTTP server
105func LoggingHandler(out io.Writer, h http.Handler, v bool, requestLoggingTpl string) http.Handler {
106 return loggingHandler{
107 writer: out,
108 handler: h,
109 enabled: v,
110 logTemplate: template.Must(template.New("request-log").Parse(requestLoggingTpl)),
111 }
114func (h loggingHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
115 t := time.Now()
116 url := *req.URL
117 logger := &responseLogger{w: w}
118 h.handler.ServeHTTP(logger, req)
119 if !h.enabled {
120 return
121 }
122 h.writeLogLine(logger.authInfo, logger.upstream, req, url, t, logger.Status(), logger.Size())
125// Log entry for req similar to Apache Common Log Format.
126// ts is the timestamp with which the entry should be logged.
127// status, size are used to provide the response HTTP status and size.
128func (h loggingHandler) writeLogLine(username, upstream string, req *http.Request, url url.URL, ts time.Time, status int, size int) {
129 if username == "" {
130 username = "-"
131 }
132 if upstream == "" {
133 upstream = "-"
134 }
135 if url.User != nil && username == "-" {
136 if name := url.User.Username(); name != "" {
137 username = name
138 }
139 }
141 client := req.Header.Get("X-Real-IP")
142 if client == "" {
143 client = req.RemoteAddr
144 }
146 if c, _, err := net.SplitHostPort(client); err == nil {
147 client = c
148 }
150 duration := float64(time.Now().Sub(ts)) / float64(time.Second)
152 h.logTemplate.Execute(h.writer, logMessageData{
153 Client: client,
154 Host: req.Host,
155 Protocol: req.Proto,
156 RequestDuration: fmt.Sprintf("%0.3f", duration),
157 RequestMethod: req.Method,
158 RequestURI: fmt.Sprintf("%q", url.RequestURI()),
159 ResponseSize: fmt.Sprintf("%d", size),
160 StatusCode: fmt.Sprintf("%d", status),
161 Timestamp: ts.Format("02/Jan/2006:15:04:05 -0700"),
162 Upstream: upstream,
163 UserAgent: fmt.Sprintf("%q", req.UserAgent()),
164 Username: username,
165 })
167 h.writer.Write([]byte("\n"))