summaryrefslogtreecommitdiffstats
path: root/modules/context/access_log.go
diff options
context:
space:
mode:
authorLunny Xiao <xiaolunwen@gmail.com>2021-01-28 01:46:35 +0800
committerGitHub <noreply@github.com>2021-01-27 18:46:35 +0100
commita51cc6dea41b154b946e982fde6cc1a600210a71 (patch)
tree07e9f38a2f3572bb8ed9a666d33dd30e976bd5e6 /modules/context/access_log.go
parent4c6e0295069a3c2f0df3d9f30560906bc2aa73a8 (diff)
downloadgitea-a51cc6dea41b154b946e982fde6cc1a600210a71.tar.gz
gitea-a51cc6dea41b154b946e982fde6cc1a600210a71.zip
Fix access log (#14475)
Fix #14121, #14478. The `AccessLog` middleware has to be after `Contexter` or `APIContexter` so that we can get `LoginUserName` if possible. And also there is a **BREAK** change that it removed internal API access log.
Diffstat (limited to 'modules/context/access_log.go')
-rw-r--r--modules/context/access_log.go60
1 files changed, 60 insertions, 0 deletions
diff --git a/modules/context/access_log.go b/modules/context/access_log.go
new file mode 100644
index 0000000000..97bb32f4c5
--- /dev/null
+++ b/modules/context/access_log.go
@@ -0,0 +1,60 @@
+// Copyright 2020 The Gitea Authors. All rights reserved.
+// Use of this source code is governed by a MIT-style
+// license that can be found in the LICENSE file.
+
+package context
+
+import (
+ "bytes"
+ "html/template"
+ "net/http"
+ "time"
+
+ "code.gitea.io/gitea/modules/log"
+ "code.gitea.io/gitea/modules/setting"
+)
+
+type routerLoggerOptions struct {
+ req *http.Request
+ Identity *string
+ Start *time.Time
+ ResponseWriter http.ResponseWriter
+ Ctx map[string]interface{}
+}
+
+// AccessLogger returns a middleware to log access logger
+func AccessLogger() func(http.Handler) http.Handler {
+ logger := log.GetLogger("access")
+ logTemplate, _ := template.New("log").Parse(setting.AccessLogTemplate)
+ return func(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ start := time.Now()
+ next.ServeHTTP(w, req)
+ identity := "-"
+ if val := SignedUserName(req); val != "" {
+ identity = val
+ }
+ rw := w.(ResponseWriter)
+
+ buf := bytes.NewBuffer([]byte{})
+ err := logTemplate.Execute(buf, routerLoggerOptions{
+ req: req,
+ Identity: &identity,
+ Start: &start,
+ ResponseWriter: rw,
+ Ctx: map[string]interface{}{
+ "RemoteAddr": req.RemoteAddr,
+ "Req": req,
+ },
+ })
+ if err != nil {
+ log.Error("Could not set up chi access logger: %v", err.Error())
+ }
+
+ err = logger.SendLog(log.INFO, "", "", 0, buf.String(), "")
+ if err != nil {
+ log.Error("Could not set up chi access logger: %v", err.Error())
+ }
+ })
+ }
+}