mirror of
https://github.com/mattermost/mattermost.git
synced 2026-02-03 20:40:00 -05:00
60 lines
1.4 KiB
Go
60 lines
1.4 KiB
Go
package logger
|
|
|
|
import (
|
|
"fmt"
|
|
"maps"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
type testLogger struct {
|
|
testing.TB
|
|
logContext LogContext
|
|
}
|
|
|
|
// NewTestLogger creates a logger for testing purposes.
|
|
func NewTestLogger() Logger {
|
|
return &testLogger{}
|
|
}
|
|
|
|
func (l *testLogger) With(logContext LogContext) Logger {
|
|
newl := *l
|
|
if len(newl.logContext) == 0 {
|
|
newl.logContext = map[string]any{}
|
|
}
|
|
maps.Copy(newl.logContext, logContext)
|
|
return &newl
|
|
}
|
|
|
|
func (l *testLogger) WithError(err error) Logger {
|
|
newl := *l
|
|
if len(newl.logContext) == 0 {
|
|
newl.logContext = map[string]any{}
|
|
}
|
|
newl.logContext[ErrorKey] = err.Error()
|
|
return &newl
|
|
}
|
|
|
|
func (l *testLogger) Context() LogContext {
|
|
return l.logContext
|
|
}
|
|
|
|
func (l *testLogger) Timed() Logger {
|
|
return l.With(LogContext{
|
|
timed: time.Now(),
|
|
})
|
|
}
|
|
|
|
func (l *testLogger) logf(prefix, format string, args ...any) {
|
|
out := fmt.Sprintf(prefix+": "+format, args...)
|
|
if len(l.logContext) > 0 {
|
|
measure(l.logContext)
|
|
out += fmt.Sprintf(" -- %+v", l.logContext)
|
|
}
|
|
l.TB.Log(out)
|
|
}
|
|
|
|
func (l *testLogger) Debugf(format string, args ...any) { l.logf("DEBUG", format, args...) }
|
|
func (l *testLogger) Errorf(format string, args ...any) { l.logf("ERROR", format, args...) }
|
|
func (l *testLogger) Infof(format string, args ...any) { l.logf("INFO", format, args...) }
|
|
func (l *testLogger) Warnf(format string, args ...any) { l.logf("WARN", format, args...) }
|