aboutsummaryrefslogtreecommitdiffstats
path: root/routers/private
diff options
context:
space:
mode:
authorwxiaoguang <wxiaoguang@gmail.com>2023-05-22 06:35:11 +0800
committerGitHub <noreply@github.com>2023-05-21 22:35:11 +0000
commit4647660776436f0a83129b4ceb8426b1fb0599bb (patch)
tree465ae0fc7cb7c4b0b30f6600a701c240cdf2a3a6 /routers/private
parent65dff8e36459a7852c40ebb4732a598ddb9bf915 (diff)
downloadgitea-4647660776436f0a83129b4ceb8426b1fb0599bb.tar.gz
gitea-4647660776436f0a83129b4ceb8426b1fb0599bb.zip
Rewrite logger system (#24726)
## ⚠️ Breaking The `log.<mode>.<logger>` style config has been dropped. If you used it, please check the new config manual & app.example.ini to make your instance output logs as expected. Although many legacy options still work, it's encouraged to upgrade to the new options. The SMTP logger is deleted because SMTP is not suitable to collect logs. If you have manually configured Gitea log options, please confirm the logger system works as expected after upgrading. ## Description Close #12082 and maybe more log-related issues, resolve some related FIXMEs in old code (which seems unfixable before) Just like rewriting queue #24505 : make code maintainable, clear legacy bugs, and add the ability to support more writers (eg: JSON, structured log) There is a new document (with examples): `logging-config.en-us.md` This PR is safer than the queue rewriting, because it's just for logging, it won't break other logic. ## The old problems The logging system is quite old and difficult to maintain: * Unclear concepts: Logger, NamedLogger, MultiChannelledLogger, SubLogger, EventLogger, WriterLogger etc * Some code is diffuclt to konw whether it is right: `log.DelNamedLogger("console")` vs `log.DelNamedLogger(log.DEFAULT)` vs `log.DelLogger("console")` * The old system heavily depends on ini config system, it's difficult to create new logger for different purpose, and it's very fragile. * The "color" trick is difficult to use and read, many colors are unnecessary, and in the future structured log could help * It's difficult to add other log formats, eg: JSON format * The log outputer doesn't have full control of its goroutine, it's difficult to make outputer have advanced behaviors * The logs could be lost in some cases: eg: no Fatal error when using CLI. * Config options are passed by JSON, which is quite fragile. * INI package makes the KEY in `[log]` section visible in `[log.sub1]` and `[log.sub1.subA]`, this behavior is quite fragile and would cause more unclear problems, and there is no strong requirement to support `log.<mode>.<logger>` syntax. ## The new design See `logger.go` for documents. ## Screenshot <details> ![image](https://github.com/go-gitea/gitea/assets/2114189/4462d713-ba39-41f5-bb08-de912e67e1ff) ![image](https://github.com/go-gitea/gitea/assets/2114189/b188035e-f691-428b-8b2d-ff7b2199b2f9) ![image](https://github.com/go-gitea/gitea/assets/2114189/132e9745-1c3b-4e00-9e0d-15eaea495dee) </details> ## TODO * [x] add some new tests * [x] fix some tests * [x] test some sub-commands (manually ....) --------- Co-authored-by: Jason Song <i@wolfogre.com> Co-authored-by: delvh <dev.lh@web.de> Co-authored-by: Giteabot <teabot@gitea.io>
Diffstat (limited to 'routers/private')
-rw-r--r--routers/private/internal.go2
-rw-r--r--routers/private/manager.go126
2 files changed, 73 insertions, 55 deletions
diff --git a/routers/private/internal.go b/routers/private/internal.go
index c6ea9e0263..b09fb58d05 100644
--- a/routers/private/internal.go
+++ b/routers/private/internal.go
@@ -73,7 +73,7 @@ func Routes() *web.Route {
r.Post("/manager/release-and-reopen-logging", ReleaseReopenLogging)
r.Post("/manager/set-log-sql", SetLogSQL)
r.Post("/manager/add-logger", bind(private.LoggerOptions{}), AddLogger)
- r.Post("/manager/remove-logger/{group}/{name}", RemoveLogger)
+ r.Post("/manager/remove-logger/{logger}/{writer}", RemoveLogger)
r.Get("/manager/processes", Processes)
r.Post("/mail/send", SendEmail)
r.Post("/restore_repo", RestoreRepo)
diff --git a/routers/private/manager.go b/routers/private/manager.go
index 38ad83326f..8ed05da6a5 100644
--- a/routers/private/manager.go
+++ b/routers/private/manager.go
@@ -10,7 +10,7 @@ import (
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/graceful"
- "code.gitea.io/gitea/modules/json"
+ "code.gitea.io/gitea/modules/graceful/releasereopen"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/private"
"code.gitea.io/gitea/modules/queue"
@@ -46,19 +46,19 @@ func FlushQueues(ctx *context.PrivateContext) {
// PauseLogging pauses logging
func PauseLogging(ctx *context.PrivateContext) {
- log.Pause()
+ log.GetManager().PauseAll()
ctx.PlainText(http.StatusOK, "success")
}
// ResumeLogging resumes logging
func ResumeLogging(ctx *context.PrivateContext) {
- log.Resume()
+ log.GetManager().ResumeAll()
ctx.PlainText(http.StatusOK, "success")
}
// ReleaseReopenLogging releases and reopens logging files
func ReleaseReopenLogging(ctx *context.PrivateContext) {
- if err := log.ReleaseReopen(); err != nil {
+ if err := releasereopen.GetManager().ReleaseReopen(); err != nil {
ctx.JSON(http.StatusInternalServerError, private.Response{
Err: fmt.Sprintf("Error during release and reopen: %v", err),
})
@@ -75,90 +75,108 @@ func SetLogSQL(ctx *context.PrivateContext) {
// RemoveLogger removes a logger
func RemoveLogger(ctx *context.PrivateContext) {
- group := ctx.Params("group")
- name := ctx.Params("name")
- ok, err := log.GetLogger(group).DelLogger(name)
+ logger := ctx.Params("logger")
+ writer := ctx.Params("writer")
+ err := log.GetManager().GetLogger(logger).RemoveWriter(writer)
if err != nil {
ctx.JSON(http.StatusInternalServerError, private.Response{
- Err: fmt.Sprintf("Failed to remove logger: %s %s %v", group, name, err),
+ Err: fmt.Sprintf("Failed to remove log writer: %s %s %v", logger, writer, err),
})
return
}
- if ok {
- setting.RemoveSubLogDescription(group, name)
- }
- ctx.PlainText(http.StatusOK, fmt.Sprintf("Removed %s %s", group, name))
+ ctx.PlainText(http.StatusOK, fmt.Sprintf("Removed %s %s", logger, writer))
}
// AddLogger adds a logger
func AddLogger(ctx *context.PrivateContext) {
opts := web.GetForm(ctx).(*private.LoggerOptions)
- if len(opts.Group) == 0 {
- opts.Group = log.DEFAULT
+
+ if len(opts.Logger) == 0 {
+ opts.Logger = log.DEFAULT
}
- if _, ok := opts.Config["flags"]; !ok {
- switch opts.Group {
+
+ writerMode := log.WriterMode{}
+ writerType := opts.Mode
+
+ var flags string
+ var ok bool
+ if flags, ok = opts.Config["flags"].(string); !ok {
+ switch opts.Logger {
case "access":
- opts.Config["flags"] = log.FlagsFromString("")
+ flags = ""
case "router":
- opts.Config["flags"] = log.FlagsFromString("date,time")
+ flags = "date,time"
default:
- opts.Config["flags"] = log.FlagsFromString("stdflags")
+ flags = "stdflags"
}
}
+ writerMode.Flags = log.FlagsFromString(flags)
- if _, ok := opts.Config["colorize"]; !ok && opts.Mode == "console" {
+ if writerMode.Colorize, ok = opts.Config["colorize"].(bool); !ok && opts.Mode == "console" {
if _, ok := opts.Config["stderr"]; ok {
- opts.Config["colorize"] = log.CanColorStderr
+ writerMode.Colorize = log.CanColorStderr
} else {
- opts.Config["colorize"] = log.CanColorStdout
+ writerMode.Colorize = log.CanColorStdout
}
}
- if _, ok := opts.Config["level"]; !ok {
- opts.Config["level"] = setting.Log.Level
+ writerMode.Level = setting.Log.Level
+ if level, ok := opts.Config["level"].(string); ok {
+ writerMode.Level = log.LevelFromString(level)
}
- if _, ok := opts.Config["stacktraceLevel"]; !ok {
- opts.Config["stacktraceLevel"] = setting.Log.StacktraceLogLevel
+ writerMode.StacktraceLevel = setting.Log.StacktraceLogLevel
+ if stacktraceLevel, ok := opts.Config["level"].(string); ok {
+ writerMode.StacktraceLevel = log.LevelFromString(stacktraceLevel)
}
- if opts.Mode == "file" {
- if _, ok := opts.Config["maxsize"]; !ok {
- opts.Config["maxsize"] = 1 << 28
+ writerMode.Prefix, _ = opts.Config["prefix"].(string)
+ writerMode.Expression, _ = opts.Config["expression"].(string)
+
+ switch writerType {
+ case "console":
+ writerOption := log.WriterConsoleOption{}
+ writerOption.Stderr, _ = opts.Config["stderr"].(bool)
+ writerMode.WriterOption = writerOption
+ case "file":
+ writerOption := log.WriterFileOption{}
+ fileName, _ := opts.Config["filename"].(string)
+ writerOption.FileName = setting.LogPrepareFilenameForWriter(fileName, opts.Writer+".log")
+ writerOption.LogRotate = opts.Config["rotate"].(bool)
+ maxSizeShift, _ := opts.Config["maxsize"].(int)
+ if maxSizeShift == 0 {
+ maxSizeShift = 28
}
- if _, ok := opts.Config["maxdays"]; !ok {
- opts.Config["maxdays"] = 7
+ writerOption.MaxSize = 1 << maxSizeShift
+ writerOption.DailyRotate, _ = opts.Config["daily"].(bool)
+ writerOption.MaxDays, _ = opts.Config["maxdays"].(int)
+ if writerOption.MaxDays == 0 {
+ writerOption.MaxDays = 7
}
- if _, ok := opts.Config["compressionLevel"]; !ok {
- opts.Config["compressionLevel"] = -1
+ writerOption.Compress, _ = opts.Config["compress"].(bool)
+ writerOption.CompressionLevel, _ = opts.Config["compressionLevel"].(int)
+ if writerOption.CompressionLevel == 0 {
+ writerOption.CompressionLevel = -1
}
+ writerMode.WriterOption = writerOption
+ case "conn":
+ writerOption := log.WriterConnOption{}
+ writerOption.ReconnectOnMsg, _ = opts.Config["reconnectOnMsg"].(bool)
+ writerOption.Reconnect, _ = opts.Config["reconnect"].(bool)
+ writerOption.Protocol, _ = opts.Config["net"].(string)
+ writerOption.Addr, _ = opts.Config["address"].(string)
+ writerMode.WriterOption = writerOption
+ default:
+ panic(fmt.Sprintf("invalid log writer mode: %s", writerType))
}
-
- bufferLen := setting.Log.BufferLength
- byteConfig, err := json.Marshal(opts.Config)
+ writer, err := log.NewEventWriter(opts.Writer, writerType, writerMode)
if err != nil {
- log.Error("Failed to marshal log configuration: %v %v", opts.Config, err)
- ctx.JSON(http.StatusInternalServerError, private.Response{
- Err: fmt.Sprintf("Failed to marshal log configuration: %v %v", opts.Config, err),
- })
- return
- }
- config := string(byteConfig)
-
- if err := log.NewNamedLogger(opts.Group, bufferLen, opts.Name, opts.Mode, config); err != nil {
- log.Error("Failed to create new named logger: %s %v", config, err)
+ log.Error("Failed to create new log writer: %v", err)
ctx.JSON(http.StatusInternalServerError, private.Response{
- Err: fmt.Sprintf("Failed to create new named logger: %s %v", config, err),
+ Err: fmt.Sprintf("Failed to create new log writer: %v", err),
})
return
}
-
- setting.AddSubLogDescription(opts.Group, setting.SubLogDescription{
- Name: opts.Name,
- Provider: opts.Mode,
- Config: config,
- })
-
+ log.GetManager().GetLogger(opts.Logger).AddWriters(writer)
ctx.PlainText(http.StatusOK, "success")
}