1// Copyright 2021 The Gitea Authors. All rights reserved.
2// Use of this source code is governed by a MIT-style
3// license that can be found in the LICENSE file.
4
5package common
6
7import (
8	"net/http"
9	"time"
10
11	"code.gitea.io/gitea/modules/context"
12	"code.gitea.io/gitea/modules/log"
13)
14
15// LoggerHandler is a handler that will log the routing to the default gitea log
16func LoggerHandler(level log.Level) func(next http.Handler) http.Handler {
17	return func(next http.Handler) http.Handler {
18		return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
19			start := time.Now()
20
21			_ = log.GetLogger("router").Log(0, level, "Started %s %s for %s", log.ColoredMethod(req.Method), req.URL.RequestURI(), req.RemoteAddr)
22
23			next.ServeHTTP(w, req)
24
25			var status int
26			if v, ok := w.(context.ResponseWriter); ok {
27				status = v.Status()
28			}
29
30			_ = log.GetLogger("router").Log(0, level, "Completed %s %s %v %s in %v", log.ColoredMethod(req.Method), req.URL.RequestURI(), log.ColoredStatus(status), log.ColoredStatus(status, http.StatusText(status)), log.ColoredTime(time.Since(start)))
31		})
32	}
33}
34