summaryrefslogtreecommitdiff
path: root/logger.go
blob: d1a22eabc3c3a7307cb6b58d4ec39158484e0a42 (plain)
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
// SPDX-FileCopyrightText: 2020 Ethel Morgan
//
// SPDX-License-Identifier: MIT

package httputil

import (
	"fmt"
	"net/http"

	"github.com/gorilla/mux"
	"go.eth.moe/logger"
)

type (
	responseWriter struct {
		http.ResponseWriter
		StatusCode int
	}
)

func (rw *responseWriter) WriteHeader(code int) {
	rw.StatusCode = code
	rw.ResponseWriter.WriteHeader(code)
}

// Logger is a middleware for logging HTTP requests and responses, using go.eth.moe/logger.
func Logger(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		log, ctx := logger.FromContext(r.Context())

		log.AddField("http.client", r.RemoteAddr)
		if xForwardedFor := r.Header.Get("X-Forwarded-For"); xForwardedFor != "" {
			log.AddField("http.client", xForwardedFor)
		}
		log.AddField("http.method", r.Method)
		log.AddField("http.path", r.URL.Path)
		log.AddField("http.useragent", r.UserAgent())

		for k, v := range mux.Vars(r) {
			log.AddField(fmt.Sprintf("http.vars.%s", k), v)
		}
		for k, vs := range r.URL.Query() {
			if len(vs) == 1 {
				log.AddField(fmt.Sprintf("http.query.%s", k), vs[0])
				continue
			}
			log.AddField(fmt.Sprintf("http.query.%s", k), vs)
		}
		for k, vs := range r.Form {
			if len(vs) == 1 {
				log.AddField(fmt.Sprintf("http.form.%s", k), vs[0])
				continue
			}
			log.AddField(fmt.Sprintf("http.form.%s", k), vs)
		}

		rw := responseWriter{ResponseWriter: w, StatusCode: 200}

		next.ServeHTTP(&rw, r.WithContext(ctx))

		log.AddField("http.status", rw.StatusCode)
		log.Info("served HTTP request")
	})
}