diff options
| author | mo khan <mo@mokhan.ca> | 2022-05-15 15:21:17 -0600 |
|---|---|---|
| committer | mo khan <mo@mokhan.ca> | 2022-05-15 15:21:17 -0600 |
| commit | e631dd1e6334d370f917e17c174b0c8d2d9f84e9 (patch) | |
| tree | 8c48ebf23e95e4b1ff3c3929f1938ed5b2b71cd7 /pkg | |
| parent | 12129cb4f0143c58a5d6c12ce905b950a0d996b5 (diff) | |
feat: add logging middleware
Diffstat (limited to 'pkg')
| -rw-r--r-- | pkg/web/default.go | 4 | ||||
| -rw-r--r-- | pkg/web/http_context.go | 29 |
2 files changed, 28 insertions, 5 deletions
diff --git a/pkg/web/default.go b/pkg/web/default.go index 9a4d89c..ac3ec8e 100644 --- a/pkg/web/default.go +++ b/pkg/web/default.go @@ -1,6 +1,8 @@ package web -import "net/http" +import ( + "net/http" +) func (h *HttpContext) Default(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) diff --git a/pkg/web/http_context.go b/pkg/web/http_context.go index 16742c7..ceabc70 100644 --- a/pkg/web/http_context.go +++ b/pkg/web/http_context.go @@ -1,28 +1,31 @@ package web import ( - "log" "net/http" + "time" + + "github.com/sirupsen/logrus" ) type HttpContext struct { issuer string keyData []byte - log *log.Logger + log *logrus.Logger } func NewHttpContext(issuer string, keyData []byte) *HttpContext { + logger := logrus.New() return &HttpContext{ issuer: issuer, keyData: keyData, - log: log.Default(), + log: logger, } } func (h *HttpContext) Router() *http.ServeMux { mux := http.NewServeMux() - mux.Handle("/", http.HandlerFunc(h.Default)) + mux.Handle("/", h.withLogging(http.HandlerFunc(h.Default))) mux.Handle("/.well-known/", h.wellKnownMux()) mux.Handle("/authorize", http.HandlerFunc(h.Authorize)) mux.Handle("/register", http.HandlerFunc(h.Register)) @@ -38,3 +41,21 @@ func (h *HttpContext) wellKnownMux() *http.ServeMux { mux.Handle("/.well-known/openid-configuration", http.HandlerFunc(h.OpenIdConfiguration)) return mux } + +func (h *HttpContext) withLogging(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + next.ServeHTTP(w, r) + end := time.Now() + + h.log.WithFields(logrus.Fields{ + "content_type": r.Header.Get("Content-Type"), + "finished_at": end.Unix(), + "method": r.Method, + "path": r.URL.Path, + "remote_addr": r.RemoteAddr, + "started_at": start.Unix(), + "user_agent": r.UserAgent, + }).Info("Done") + }) +} |
