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>
2023-05-22 06:35:11 +08:00
|
|
|
// Copyright 2023 The Gitea Authors. All rights reserved.
|
|
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
|
|
|
|
package log
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"runtime"
|
|
|
|
"strings"
|
|
|
|
"sync"
|
|
|
|
"sync/atomic"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"code.gitea.io/gitea/modules/json"
|
|
|
|
"code.gitea.io/gitea/modules/util"
|
|
|
|
)
|
|
|
|
|
|
|
|
type LoggerImpl struct {
|
|
|
|
LevelLogger
|
|
|
|
|
|
|
|
ctx context.Context
|
|
|
|
ctxCancel context.CancelFunc
|
|
|
|
|
|
|
|
level atomic.Int32
|
|
|
|
stacktraceLevel atomic.Int32
|
|
|
|
|
|
|
|
eventWriterMu sync.RWMutex
|
|
|
|
eventWriters map[string]EventWriter
|
|
|
|
}
|
|
|
|
|
|
|
|
var (
|
|
|
|
_ BaseLogger = (*LoggerImpl)(nil)
|
|
|
|
_ LevelLogger = (*LoggerImpl)(nil)
|
|
|
|
)
|
|
|
|
|
|
|
|
// SendLogEvent sends a log event to all writers
|
|
|
|
func (l *LoggerImpl) SendLogEvent(event *Event) {
|
|
|
|
l.eventWriterMu.RLock()
|
|
|
|
defer l.eventWriterMu.RUnlock()
|
|
|
|
|
|
|
|
if len(l.eventWriters) == 0 {
|
|
|
|
FallbackErrorf("[no logger writer]: %s", event.MsgSimpleText)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// the writers have their own goroutines, the message arguments (with Stringer) shouldn't be used in other goroutines
|
|
|
|
// so the event message must be formatted here
|
|
|
|
msgFormat, msgArgs := event.msgFormat, event.msgArgs
|
|
|
|
event.msgFormat, event.msgArgs = "(already processed by formatters)", nil
|
|
|
|
|
|
|
|
for _, w := range l.eventWriters {
|
|
|
|
if event.Level < w.GetLevel() {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
formatted := &EventFormatted{
|
|
|
|
Origin: event,
|
|
|
|
Msg: w.Base().FormatMessage(w.Base().Mode, event, msgFormat, msgArgs...),
|
|
|
|
}
|
|
|
|
select {
|
|
|
|
case w.Base().Queue <- formatted:
|
|
|
|
default:
|
|
|
|
bs, _ := json.Marshal(event)
|
|
|
|
FallbackErrorf("log writer %q queue is full, event: %v", w.GetWriterName(), string(bs))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// syncLevelInternal syncs the level of the logger with the levels of the writers
|
|
|
|
func (l *LoggerImpl) syncLevelInternal() {
|
|
|
|
lowestLevel := NONE
|
|
|
|
for _, w := range l.eventWriters {
|
|
|
|
if w.GetLevel() < lowestLevel {
|
|
|
|
lowestLevel = w.GetLevel()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
l.level.Store(int32(lowestLevel))
|
|
|
|
|
|
|
|
lowestLevel = NONE
|
|
|
|
for _, w := range l.eventWriters {
|
|
|
|
if w.Base().Mode.StacktraceLevel < lowestLevel {
|
|
|
|
lowestLevel = w.GetLevel()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
l.stacktraceLevel.Store(int32(lowestLevel))
|
|
|
|
}
|
|
|
|
|
|
|
|
// removeWriterInternal removes a writer from the logger, and stops it if it's not shared
|
|
|
|
func (l *LoggerImpl) removeWriterInternal(w EventWriter) {
|
|
|
|
if !w.Base().shared {
|
|
|
|
eventWriterStopWait(w) // only stop non-shared writers, shared writers are managed by the manager
|
|
|
|
}
|
|
|
|
delete(l.eventWriters, w.GetWriterName())
|
|
|
|
}
|
|
|
|
|
|
|
|
// AddWriters adds writers to the logger, and starts them. Existing writers will be replaced by new ones.
|
|
|
|
func (l *LoggerImpl) AddWriters(writer ...EventWriter) {
|
|
|
|
l.eventWriterMu.Lock()
|
|
|
|
defer l.eventWriterMu.Unlock()
|
|
|
|
|
|
|
|
for _, w := range writer {
|
|
|
|
if old, ok := l.eventWriters[w.GetWriterName()]; ok {
|
|
|
|
l.removeWriterInternal(old)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, w := range writer {
|
|
|
|
l.eventWriters[w.GetWriterName()] = w
|
|
|
|
eventWriterStartGo(l.ctx, w, false)
|
|
|
|
}
|
|
|
|
|
|
|
|
l.syncLevelInternal()
|
|
|
|
}
|
|
|
|
|
|
|
|
// RemoveWriter removes a writer from the logger, and the writer is closed and flushed if it is not shared
|
|
|
|
func (l *LoggerImpl) RemoveWriter(modeName string) error {
|
|
|
|
l.eventWriterMu.Lock()
|
|
|
|
defer l.eventWriterMu.Unlock()
|
|
|
|
|
|
|
|
w, ok := l.eventWriters[modeName]
|
|
|
|
if !ok {
|
|
|
|
return util.ErrNotExist
|
|
|
|
}
|
|
|
|
|
|
|
|
l.removeWriterInternal(w)
|
|
|
|
l.syncLevelInternal()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// RemoveAllWriters removes all writers from the logger, non-shared writers are closed and flushed
|
|
|
|
func (l *LoggerImpl) RemoveAllWriters() *LoggerImpl {
|
|
|
|
l.eventWriterMu.Lock()
|
|
|
|
defer l.eventWriterMu.Unlock()
|
|
|
|
|
|
|
|
for _, w := range l.eventWriters {
|
|
|
|
l.removeWriterInternal(w)
|
|
|
|
}
|
|
|
|
l.eventWriters = map[string]EventWriter{}
|
|
|
|
l.syncLevelInternal()
|
|
|
|
return l
|
|
|
|
}
|
|
|
|
|
|
|
|
// DumpWriters dumps the writers as a JSON map, it's used for debugging and display purposes.
|
|
|
|
func (l *LoggerImpl) DumpWriters() map[string]any {
|
|
|
|
l.eventWriterMu.RLock()
|
|
|
|
defer l.eventWriterMu.RUnlock()
|
|
|
|
|
|
|
|
writers := make(map[string]any, len(l.eventWriters))
|
|
|
|
for k, w := range l.eventWriters {
|
|
|
|
bs, err := json.Marshal(w.Base().Mode)
|
|
|
|
if err != nil {
|
|
|
|
FallbackErrorf("marshal writer %q to dump failed: %v", k, err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
m := map[string]any{}
|
|
|
|
_ = json.Unmarshal(bs, &m)
|
|
|
|
m["WriterType"] = w.GetWriterType()
|
|
|
|
writers[k] = m
|
|
|
|
}
|
|
|
|
return writers
|
|
|
|
}
|
|
|
|
|
|
|
|
// Close closes the logger, non-shared writers are closed and flushed
|
|
|
|
func (l *LoggerImpl) Close() {
|
|
|
|
l.RemoveAllWriters()
|
|
|
|
l.ctxCancel()
|
|
|
|
}
|
|
|
|
|
|
|
|
// IsEnabled returns true if the logger is enabled: it has a working level and has writers
|
|
|
|
// Fatal is not considered as enabled, because it's a special case and the process just exits
|
|
|
|
func (l *LoggerImpl) IsEnabled() bool {
|
|
|
|
l.eventWriterMu.RLock()
|
|
|
|
defer l.eventWriterMu.RUnlock()
|
|
|
|
return l.level.Load() < int32(FATAL) && len(l.eventWriters) > 0
|
|
|
|
}
|
|
|
|
|
|
|
|
// Log prepares the log event, if the level matches, the event will be sent to the writers
|
|
|
|
func (l *LoggerImpl) Log(skip int, level Level, format string, logArgs ...any) {
|
|
|
|
if Level(l.level.Load()) > level {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
event := &Event{
|
|
|
|
Time: time.Now(),
|
|
|
|
Level: level,
|
|
|
|
Caller: "?()",
|
|
|
|
}
|
|
|
|
|
|
|
|
pc, filename, line, ok := runtime.Caller(skip + 1)
|
|
|
|
if ok {
|
|
|
|
fn := runtime.FuncForPC(pc)
|
|
|
|
if fn != nil {
|
|
|
|
event.Caller = fn.Name() + "()"
|
|
|
|
}
|
|
|
|
}
|
|
|
|
event.Filename, event.Line = strings.TrimPrefix(filename, projectPackagePrefix), line
|
|
|
|
|
|
|
|
if l.stacktraceLevel.Load() <= int32(level) {
|
|
|
|
event.Stacktrace = Stack(skip + 1)
|
|
|
|
}
|
|
|
|
|
|
|
|
labels := getGoroutineLabels()
|
|
|
|
if labels != nil {
|
|
|
|
event.GoroutinePid = labels["pid"]
|
|
|
|
}
|
|
|
|
|
|
|
|
// get a simple text message without color
|
|
|
|
msgArgs := make([]any, len(logArgs))
|
|
|
|
copy(msgArgs, logArgs)
|
|
|
|
|
|
|
|
// handle LogStringer values
|
|
|
|
for i, v := range msgArgs {
|
|
|
|
if cv, ok := v.(*ColoredValue); ok {
|
|
|
|
if s, ok := cv.v.(LogStringer); ok {
|
|
|
|
cv.v = logStringFormatter{v: s}
|
|
|
|
}
|
|
|
|
} else if s, ok := v.(LogStringer); ok {
|
|
|
|
msgArgs[i] = logStringFormatter{v: s}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
event.MsgSimpleText = colorSprintf(false, format, msgArgs...)
|
|
|
|
event.msgFormat = format
|
|
|
|
event.msgArgs = msgArgs
|
|
|
|
l.SendLogEvent(event)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (l *LoggerImpl) GetLevel() Level {
|
|
|
|
return Level(l.level.Load())
|
|
|
|
}
|
|
|
|
|
Improve queue and logger context (#24924)
Before there was a "graceful function": RunWithShutdownFns, it's mainly
for some modules which doesn't support context.
The old queue system doesn't work well with context, so the old queues
need it.
After the queue refactoring, the new queue works with context well, so,
use Golang context as much as possible, the `RunWithShutdownFns` could
be removed (replaced by RunWithCancel for context cancel mechanism), the
related code could be simplified.
This PR also fixes some legacy queue-init problems, eg:
* typo : archiver: "unable to create codes indexer queue" => "unable to
create repo-archive queue"
* no nil check for failed queues, which causes unfriendly panic
After this PR, many goroutines could have better display name:
![image](https://github.com/go-gitea/gitea/assets/2114189/701b2a9b-8065-4137-aeaa-0bda2b34604a)
![image](https://github.com/go-gitea/gitea/assets/2114189/f1d5f50f-0534-40f0-b0be-f2c9daa5fe92)
2023-05-26 15:31:55 +08:00
|
|
|
func NewLoggerWithWriters(ctx context.Context, name string, writer ...EventWriter) *LoggerImpl {
|
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>
2023-05-22 06:35:11 +08:00
|
|
|
l := &LoggerImpl{}
|
2023-05-27 18:55:24 +08:00
|
|
|
l.ctx, l.ctxCancel = newProcessTypedContext(ctx, "Logger: "+name)
|
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>
2023-05-22 06:35:11 +08:00
|
|
|
l.LevelLogger = BaseLoggerToGeneralLogger(l)
|
|
|
|
l.eventWriters = map[string]EventWriter{}
|
|
|
|
l.syncLevelInternal()
|
|
|
|
l.AddWriters(writer...)
|
|
|
|
return l
|
|
|
|
}
|