Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor Router Logger #17308

Merged
merged 58 commits into from
Jan 20, 2022
Merged
Show file tree
Hide file tree
Changes from 30 commits
Commits
Show all changes
58 commits
Select commit Hold shift + click to select a range
81fc293
introduce router log handler v2
wxiaoguang Oct 18, 2021
1bedc91
Merge branch 'main' into optimize-logger
wxiaoguang Oct 18, 2021
9a7017e
add comment about performance
wxiaoguang Oct 18, 2021
298c1b9
Merge branch 'main' into optimize-logger
wxiaoguang Oct 19, 2021
ce63306
fix
wxiaoguang Oct 19, 2021
5f67c98
Merge branch 'main' into optimize-logger
wxiaoguang Oct 19, 2021
3942088
Merge remote-tracking branch 'origin/main' into optimize-logger
zeripath Oct 19, 2021
22b13f2
Add some comments and a test
zeripath Oct 19, 2021
be8af1a
apply suggestion
wxiaoguang Oct 20, 2021
a485d9d
Merge branch 'optimize-logger' of github.com:wxiaoguang/gitea into op…
wxiaoguang Oct 20, 2021
32a6690
Merge remote-tracking branch 'go-gitea/main' into optimize-logger
wxiaoguang Oct 20, 2021
af90a2c
Merge branch 'main' into optimize-logger
wxiaoguang Oct 21, 2021
fd46839
Merge branch 'main' into optimize-logger
wxiaoguang Oct 21, 2021
ebaee13
Merge branch 'main' into optimize-logger
wxiaoguang Oct 21, 2021
2f40634
Merge branch 'main' into optimize-logger
wxiaoguang Oct 28, 2021
ffc86fb
Merge remote-tracking branch 'zeripath/optimize-logger' into optimize…
wxiaoguang Oct 28, 2021
3eff51e
tune comments
wxiaoguang Oct 28, 2021
cca722c
we can use `time.NewTicker` safely and it reduces memory allocations.
wxiaoguang Oct 28, 2021
05de541
tune tests
wxiaoguang Oct 28, 2021
90ce83c
Merge branch 'main' into optimize-logger
wxiaoguang Nov 9, 2021
e7a5b6f
Merge branch 'main' into optimize-logger
wxiaoguang Nov 10, 2021
84768f6
Merge branch 'main' into optimize-logger
wxiaoguang Nov 13, 2021
a3de079
Merge branch 'main' into optimize-logger
wxiaoguang Nov 17, 2021
e3e212d
Merge branch 'main' into optimize-logger
wxiaoguang Nov 19, 2021
354127e
Merge remote-tracking branch 'go-gitea/main' into optimize-logger
wxiaoguang Nov 19, 2021
a0bc540
Merge branch 'main' into optimize-logger
wxiaoguang Nov 24, 2021
3bddad9
Merge branch 'main' into optimize-logger
wxiaoguang Dec 1, 2021
c2032bd
Fix merge
wxiaoguang Dec 1, 2021
afd3200
make the duration more readable
wxiaoguang Dec 1, 2021
90ead72
Merge branch 'main' into optimize-logger
wxiaoguang Dec 10, 2021
c92c4e9
Merge branch 'main' into optimize-logger
wxiaoguang Dec 20, 2021
f5332d8
Merge branch 'main' into optimize-logger
wxiaoguang Dec 21, 2021
8dafc18
show "started" message in DEBUG level, show long-polling message
wxiaoguang Dec 22, 2021
7a743f1
Merge branch 'main' into optimize-logger
wxiaoguang Dec 22, 2021
cb989fe
fix lint
wxiaoguang Dec 22, 2021
81ca64a
add comment
wxiaoguang Dec 22, 2021
bce0875
better format
wxiaoguang Dec 22, 2021
65a48bd
Generate FuncInfo outside of handlers and pre-wrap handlers
zeripath Dec 22, 2021
24760ed
Update messages
zeripath Dec 22, 2021
142957f
ourHandlerFunc -> wrappedHandlerFunc
zeripath Dec 23, 2021
e506e3e
move wrap to web
zeripath Dec 23, 2021
4836f06
Remove IsEnabledOn
zeripath Dec 23, 2021
bf08538
Move the requestrecord infrastructure to modules/web/routing
zeripath Dec 23, 2021
d3e6ded
Merge pull request #3 from zeripath/optimize-logger
wxiaoguang Dec 23, 2021
37d7928
fix comment for logger v1
wxiaoguang Dec 23, 2021
6d14aac
Improve app.example.ini and document, refactor wrap and router logger
wxiaoguang Dec 23, 2021
a284f30
fix documents and comments
wxiaoguang Dec 23, 2021
34ddd09
Merge branch 'main' into optimize-logger
wxiaoguang Dec 23, 2021
9f34791
fix log.ACCESS
wxiaoguang Dec 24, 2021
f7fe8a7
revert document
wxiaoguang Dec 24, 2021
78afbc0
Merge branch 'main' into optimize-logger
wxiaoguang Dec 25, 2021
4cb7e03
Remove logger v1
zeripath Dec 26, 2021
f0d5559
Merge pull request #5 from zeripath/optimize-logger-no-logger-v1
wxiaoguang Jan 20, 2022
00da10b
Merge branch 'main' into optimize-logger
wxiaoguang Jan 20, 2022
8d143fe
fix broken conflicts resolution
zeripath Jan 20, 2022
3e77481
Merge branch 'main' into optimize-logger
wxiaoguang Jan 20, 2022
f2cfdcf
Use TRACE level to show router started message
wxiaoguang Jan 20, 2022
5a39871
Fix document
wxiaoguang Jan 20, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cmd/web.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ func runWeb(ctx *cli.Context) error {
}
defer func() {
if panicked := recover(); panicked != nil {
log.Fatal("PANIC: %v\n%s", panicked, string(log.Stack(2)))
log.Fatal("PANIC: %v\n%s", panicked, log.Stack(2))
}
}()

Expand Down
3 changes: 3 additions & 0 deletions custom/conf/app.example.ini
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +469,9 @@ ROUTER = console
;; The level at which the router logs
;ROUTER_LOG_LEVEL = Info
;;
;; The handler for router logs, it controls the log format
;ROUTER_LOG_HANDLER = v2
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Access Logger (Creates log in NCSA common log format)
Expand Down
3 changes: 2 additions & 1 deletion docs/content/doc/advanced/config-cheat-sheet.en-us.md
Original file line number Diff line number Diff line change
Expand Up @@ -750,7 +750,8 @@ Default templates for project boards:
- `MODE`: **console**: Logging mode. For multiple modes, use a comma to separate values. You can configure each mode in per mode log subsections `\[log.modename\]`. By default the file mode will log to `$ROOT_PATH/gitea.log`.
- `LEVEL`: **Info**: General log level. \[Trace, Debug, Info, Warn, Error, Critical, Fatal, None\]
- `STACKTRACE_LEVEL`: **None**: Default log level at which to log create stack traces. \[Trace, Debug, Info, Warn, Error, Critical, Fatal, None\]
- `ROUTER_LOG_LEVEL`: **Info**: The log level that the router should log at. (If you are setting the access log, its recommended to place this at Debug.)
- `ROUTER_LOG_LEVEL`: **Info**: The log level that the router should log at. (If you are setting the access log, it's recommended to place this at Debug.)
- `ROUTER_LOG_HANDLER`: **v2**: The log handler that controls the log output format. Before 1.16 the router logs are outputted by handler `v1`. From 1.16, the default handler is `v2` which is more meaningful and friendly.
- `ROUTER`: **console**: The mode or name of the log the router should log to. (If you set this to `,` it will log to default Gitea logger.)
NB: You must have `DISABLE_ROUTER_LOG` set to `false` for this option to take effect. Configure each mode in per mode log subsections `\[log.modename.router\]`.
- `ENABLE_ACCESS_LOG`: **false**: Creates an access.log in NCSA common log format, or as per the following template
Expand Down
7 changes: 7 additions & 0 deletions docs/content/doc/advanced/logging-documentation.en-us.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,13 @@ changed if desired by setting the `ROUTER_LOG_LEVEL` value.
Please note, setting the `LEVEL` of this logger to a level above
`ROUTER_LOG_LEVEL` will result in no router logs.

You can control the output format by setting a log handler to `ROUTER_LOG_HANDLER`.
Now Gitea has two log handlers:
* `v1` is the default handler for Gitea before 1.16
* `v2` is the default handler for Gitea from 1.16, it's more meaningful and friendly.

If you have applications depending on the log format (eg: fail2ban), please make sure you use the correct log handler and log format.

Each output sublogger for this logger is configured in
`[log.sublogger.router]` sections. There are certain default values
which will not be inherited from the `[log]` or relevant
Expand Down
11 changes: 8 additions & 3 deletions modules/log/colors_router.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package log

import (
"fmt"
"time"
)

Expand Down Expand Up @@ -72,12 +73,16 @@ var (
wayTooLong = ColorBytes(BgMagenta)
)

// ColoredTime adds colors for time on log
// ColoredTime adds colors for time on log, it always formats the duration in Millisecond unit
func ColoredTime(duration time.Duration) *ColoredValue {
// the output of in Millisecond is more readable:
// * before: "100.1ms" "100.1μs" "100.1s"
// * better: "100.1ms" "0.1ms" "100100.0ms", readers can compare the values at first glance.
str := fmt.Sprintf("%.1fms", float64(duration.Microseconds())/1000)
for i, k := range durations {
if duration < k {
return NewColoredValueBytes(duration, &durationColors[i])
return NewColoredValueBytes(str, &durationColors[i])
}
}
return NewColoredValueBytes(duration, &wayTooLong)
return NewColoredValueBytes(str, &wayTooLong)
}
89 changes: 43 additions & 46 deletions modules/public/public.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,11 @@ type Options struct {
CorsHandler func(http.Handler) http.Handler
}

// AssetsHandler implements the static handler for serving custom or original assets.
func AssetsHandler(opts *Options) func(next http.Handler) http.Handler {
// AssetsURLPathPrefix is the path prefix for static asset files
const AssetsURLPathPrefix = "/assets/"

// AssetsHandlerFunc implements the static handler for serving custom or original assets.
func AssetsHandlerFunc(opts *Options) http.HandlerFunc {
var custPath = filepath.Join(setting.CustomPath, "public")
if !filepath.IsAbs(custPath) {
custPath = filepath.Join(setting.AppWorkPath, custPath)
Expand All @@ -36,52 +39,46 @@ func AssetsHandler(opts *Options) func(next http.Handler) http.Handler {
opts.Prefix += "/"
}

return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
if !strings.HasPrefix(req.URL.Path, opts.Prefix) {
next.ServeHTTP(resp, req)
return
}
if req.Method != "GET" && req.Method != "HEAD" {
resp.WriteHeader(http.StatusNotFound)
return
}

file := req.URL.Path
file = file[len(opts.Prefix):]
if len(file) == 0 {
resp.WriteHeader(http.StatusNotFound)
return
}
if strings.Contains(file, "\\") {
resp.WriteHeader(http.StatusBadRequest)
return
}
file = "/" + file

var written bool
if opts.CorsHandler != nil {
written = true
opts.CorsHandler(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
written = false
})).ServeHTTP(resp, req)
}
if written {
return
}

// custom files
if opts.handle(resp, req, http.Dir(custPath), file) {
return
}

// internal files
if opts.handle(resp, req, fileSystem(opts.Directory), file) {
return
}
return func(resp http.ResponseWriter, req *http.Request) {
if req.Method != "GET" && req.Method != "HEAD" {
resp.WriteHeader(http.StatusNotFound)
return
}

file := req.URL.Path
file = file[len(opts.Prefix):]
if len(file) == 0 {
resp.WriteHeader(http.StatusNotFound)
})
return
}
if strings.Contains(file, "\\") {
resp.WriteHeader(http.StatusBadRequest)
return
}
file = "/" + file

var written bool
if opts.CorsHandler != nil {
written = true
opts.CorsHandler(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
written = false
})).ServeHTTP(resp, req)
}
if written {
return
}

// custom files
if opts.handle(resp, req, http.Dir(custPath), file) {
return
}

// internal files
if opts.handle(resp, req, fileSystem(opts.Directory), file) {
return
}

resp.WriteHeader(http.StatusNotFound)
}
}

Expand Down
1 change: 1 addition & 0 deletions modules/setting/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ func getStacktraceLogLevel(section *ini.Section, key string, defaultValue string

func generateLogConfig(sec *ini.Section, name string, defaults defaultLogOptions) (mode, jsonConfig, levelName string) {
level := getLogLevel(sec, "LEVEL", LogLevel)
levelName = level.String()
wxiaoguang marked this conversation as resolved.
Show resolved Hide resolved
stacktraceLevelName := getStacktraceLogLevel(sec, "STACKTRACE_LEVEL", StacktraceLogLevel)
stacktraceLevel := log.FromString(stacktraceLevelName)
mode = name
Expand Down
2 changes: 2 additions & 0 deletions modules/setting/setting.go
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,7 @@ var (
LogRootPath string
DisableRouterLog bool
RouterLogLevel log.Level
RouterLogHandler string
EnableAccessLog bool
EnableSSHLog bool
AccessLogTemplate string
Expand Down Expand Up @@ -604,6 +605,7 @@ func loadFromConf(allowEmpty bool, extraConfig string) {
LogRootPath = Cfg.Section("log").Key("ROOT_PATH").MustString(path.Join(AppWorkPath, "log"))
forcePathSeparator(LogRootPath)
RouterLogLevel = log.FromString(Cfg.Section("log").Key("ROUTER_LOG_LEVEL").MustString("Info"))
RouterLogHandler = Cfg.Section("log").Key("ROUTER_LOG_HANDLER").MustString("v2")

sec := Cfg.Section("server")
AppName = Cfg.Section("").Key("APP_NAME").MustString("Gitea: Git with a cup of tea")
Expand Down
2 changes: 2 additions & 0 deletions modules/web/route.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (

"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/web/middleware"
"code.gitea.io/gitea/routers/common"

"gitea.com/go-chi/binding"
chi "github.com/go-chi/chi/v5"
Expand Down Expand Up @@ -40,6 +41,7 @@ func Wrap(handlers ...interface{}) http.HandlerFunc {
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
for i := 0; i < len(handlers); i++ {
handler := handlers[i]
common.UpdateContextHandlerFuncInfo(req.Context(), handler)
switch t := handler.(type) {
case http.HandlerFunc:
t(resp, req)
Expand Down
4 changes: 2 additions & 2 deletions routers/common/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ import (
"code.gitea.io/gitea/modules/log"
)

// LoggerHandler is a handler that will log the routing to the default gitea log
func LoggerHandler(level log.Level) func(next http.Handler) http.Handler {
// NewLoggerHandlerV1 is a handler that will log the routing to the default gitea log
func NewLoggerHandlerV1(level log.Level) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
start := time.Now()
Expand Down
Loading