diff --git a/box.go b/box.go index b0b5d34..e9cc8ee 100644 --- a/box.go +++ b/box.go @@ -5,8 +5,8 @@ import ( "github.com/echocat/goxr/box/fs" "github.com/echocat/goxr/box/packed" "github.com/echocat/goxr/common" - "github.com/echocat/goxr/log" "github.com/echocat/goxr/runtime" + "github.com/echocat/slf4g" "io" "path/filepath" sr "runtime" @@ -16,7 +16,7 @@ import ( type OnFallbackToFsBoxFunc func(packedBoxCandidateFilename string, bases []string, fsBox Box) error var ( - // This variable could easily set while build time using: + // AllowFallbackToFsBox could easily set while build time using: // go build -ldflags="-X github.com/echocat/goxr.AllowFallbackToFsBox=false" . // This is useful in case for behave differently for build versions of you application AllowFallbackToFsBox = true @@ -104,21 +104,22 @@ func resolveCallingDir(skipCallerFrames int) string { return result } -//noinspection GoSnakeCaseUsage -func OnFallbackToFsBox_Default(packedBoxCandidateFilename string, bases []string, fsBox Box) error { +// noinspection GoSnakeCaseUsage +var OnFallbackToFsBox_Default = func(packedBoxCandidateFilename string, bases []string, fsBox Box) error { if AllowFallbackToFsBox { return OnFallbackToFsBox_Warn(packedBoxCandidateFilename, bases, fsBox) } return OnFallbackToFsBox_Fail(packedBoxCandidateFilename, bases, fsBox) } -//noinspection GoSnakeCaseUsage -func OnFallbackToFsBox_Warn(packedBoxCandidateFilename string, bases []string, fsBox Box) error { - log.Warnf("%s does not contain a packed box version. This could happen in development mode", packedBoxCandidateFilename) +// noinspection GoSnakeCaseUsage +var OnFallbackToFsBox_Warn = func(packedBoxCandidateFilename string, bases []string, fsBox Box) error { + log.With("candidate", packedBoxCandidateFilename). + Warn("Candidate does not contain a packed box version. This could happen in development mode.") return nil } -//noinspection GoSnakeCaseUsage -func OnFallbackToFsBox_Fail(packedBoxCandidateFilename string, bases []string, fsBox Box) error { +// noinspection GoSnakeCaseUsage +var OnFallbackToFsBox_Fail = func(packedBoxCandidateFilename string, bases []string, fsBox Box) error { return common.NewPathError("openBox", packedBoxCandidateFilename, common.ErrDoesNotContainBox) } diff --git a/common/cli.go b/common/cli.go index a081064..aa1ff4f 100644 --- a/common/cli.go +++ b/common/cli.go @@ -1,8 +1,9 @@ package common import ( - "github.com/echocat/goxr/log" "github.com/echocat/goxr/runtime" + "github.com/echocat/slf4g" + _ "github.com/echocat/slf4g/native" "github.com/urfave/cli" "net/http" _ "net/http/pprof" @@ -128,12 +129,10 @@ func NewApp() *cli.App { func cliXpprofHandler() { if cliXpprofListen != "" { go func() { - log.WithField("listenAddress", cliXpprofListen). - Warnf("DO NOT USE IN PRODUCTION!"+ - " pprof server was activated for debugging at listen address %s."+ - " This functionality is only for debug purposes.", - cliXpprofListen, - ) + log.With("listenAddress", cliXpprofListen). + Warnf("DO NOT USE IN PRODUCTION!" + + " pprof server was activated for debugging at listen address." + + " This functionality is only for debug purposes.") if err := http.ListenAndServe(cliXpprofListen, nil); err != nil { panic(err) } diff --git a/go.mod b/go.mod index 812e9e3..82e0e29 100644 --- a/go.mod +++ b/go.mod @@ -2,9 +2,10 @@ module github.com/echocat/goxr require ( github.com/c2h5oh/datasize v0.0.0-20200112174442-28bbd4740fee // performance tests + github.com/echocat/slf4g v1.5.2 + github.com/echocat/slf4g/native v1.5.2 github.com/edsrzf/mmap-go v1.1.0 github.com/pkg/errors v0.9.1 - github.com/sirupsen/logrus v1.9.3 github.com/stretchr/testify v1.8.4 github.com/urfave/cli v1.22.14 github.com/valyala/fasthttp v1.50.0 diff --git a/go.sum b/go.sum index 7b64d84..84df094 100644 --- a/go.sum +++ b/go.sum @@ -8,6 +8,11 @@ github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46t github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/echocat/slf4g v0.0.0/go.mod h1:R4ge09pgerMnd/bJQeKVFm4igVYgJW6CqfUOzT/CA10= +github.com/echocat/slf4g v1.5.2 h1:QBdnMI95Ju9j0VHsZ7IHGFKqrsF1EBN1n9EqWIjM4dw= +github.com/echocat/slf4g v1.5.2/go.mod h1:YvF/d1TcPvT+/xiHStLHPI4xPT1GGeEmPczn2MSljNA= +github.com/echocat/slf4g/native v1.5.2 h1:DFXpybP8d3GcflOngj0H7NymJ+McJanNlQRxWL9yEfA= +github.com/echocat/slf4g/native v1.5.2/go.mod h1:vCZn/wnp0xfdXlm5W1DwJI2SaLBc6NKaAqtNqe1y0VY= github.com/edsrzf/mmap-go v1.1.0 h1:6EUwBLQ/Mcr1EYLE4Tn1VdW1A4ckqCQWZBw8Hr0kjpQ= github.com/edsrzf/mmap-go v1.1.0/go.mod h1:19H/e8pUPLicwkyNgOykDXkJ9F0MHE+Z52B8EIth78Q= github.com/golang/protobuf v1.3.1 h1:YF8+flBXS5eO826T4nzqPrxfhQThhXl0YzfuUPu4SBg= @@ -20,12 +25,9 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= -github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= @@ -60,11 +62,11 @@ golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE= +golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= diff --git a/log/colormode.go b/log/colormode.go deleted file mode 100644 index 8502a64..0000000 --- a/log/colormode.go +++ /dev/null @@ -1,44 +0,0 @@ -package log - -import ( - "fmt" - "strings" -) - -type ColorMode string - -const ( - DefaultColorMode = ColorMode("") - AutoColorMode = ColorMode("auto") - NeverColorMode = ColorMode("never") - AlwaysColorMode = ColorMode("always") -) - -var AllColorModes = []ColorMode{ - AutoColorMode, - NeverColorMode, - AlwaysColorMode, -} - -func (instance *ColorMode) Set(plain string) error { - for _, candidate := range AllColorModes { - if candidate.String() == plain { - *instance = candidate - return nil - } - } - switch plain { - case "default": - *instance = DefaultColorMode - return nil - } - allStr := make([]string, len(AllColorModes)) - for i, v := range AllColorModes { - allStr[i] = v.String() - } - return fmt.Errorf("illegal log color mode '%s' (possible values are: %s)", plain, strings.Join(allStr, ",")) -} - -func (instance ColorMode) String() string { - return string(instance) -} diff --git a/log/configuration.go b/log/configuration.go deleted file mode 100644 index bf91f25..0000000 --- a/log/configuration.go +++ /dev/null @@ -1,81 +0,0 @@ -package log - -import "github.com/urfave/cli" - -type Configuration struct { - Level Level `yaml:"level" json:"level"` - Format Format `yaml:"format" json:"format"` - ReportCaller bool `yaml:"reportCaller,omitempty" json:"reportCaller,omitempty"` - ColorMode ColorMode `yaml:"colorMode" json:"colorMode" ` -} - -func (instance Configuration) Merge(with Configuration) Configuration { - result := instance - if with.Level != DefaultLevel { - result.Level = with.Level - } - if with.Format != DefaultFormat { - result.Format = with.Format - } - if with.ReportCaller { - result.ReportCaller = with.ReportCaller - } - if with.ColorMode != DefaultColorMode { - result.ColorMode = with.ColorMode - } - return result -} - -func (instance Configuration) GetLevel(def Level) Level { - if result := instance.Level; result != DefaultLevel { - return result - } - return def -} - -func (instance Configuration) GetFormat(def Format) Format { - if result := instance.Format; result != DefaultFormat { - return result - } - return def -} - -func (instance Configuration) GetReportCaller() bool { - return instance.ReportCaller -} - -func (instance Configuration) GetColorMode(def ColorMode) ColorMode { - if result := instance.ColorMode; result != DefaultColorMode { - return result - } - return def -} - -func (instance *Configuration) Flags() []cli.Flag { - return []cli.Flag{ - cli.GenericFlag{ - Name: "logLevel", - Usage: "Specifies the minimum required log level.", - EnvVar: "GOXR_LOG_LEVEL", - Value: &instance.Level, - }, - cli.GenericFlag{ - Name: "logFormat", - Usage: "Specifies format output (text or json).", - EnvVar: "GOXR_LOG_FORMAT", - Value: &instance.Format, - }, - cli.GenericFlag{ - Name: "logColorMode", - Usage: "Specifies if the output is in colors or not (auto, never or always).", - EnvVar: "GOXR_COLOR_MODE", - Value: &instance.ColorMode, - }, - cli.BoolFlag{ - Name: "logCaller", - Usage: "If true the caller details will be logged too.", - EnvVar: "GOXR_LOG_CALLER", - Destination: &instance.ReportCaller, - }, - } -} diff --git a/log/format.go b/log/format.go deleted file mode 100644 index 4847633..0000000 --- a/log/format.go +++ /dev/null @@ -1,42 +0,0 @@ -package log - -import ( - "fmt" - "strings" -) - -type Format string - -const ( - DefaultFormat = Format("") - TextFormat = Format("text") - JsonFormat = Format("json") -) - -var AllFormats = []Format{ - TextFormat, - JsonFormat, -} - -func (instance *Format) Set(plain string) error { - for _, candidate := range AllFormats { - if candidate.String() == plain { - *instance = candidate - return nil - } - } - switch plain { - case "default": - *instance = DefaultFormat - return nil - } - allStr := make([]string, len(AllFormats)) - for i, v := range AllFormats { - allStr[i] = v.String() - } - return fmt.Errorf("illegal log format '%s' (possible values are: %s)", plain, strings.Join(allStr, ",")) -} - -func (instance Format) String() string { - return string(instance) -} diff --git a/log/level.go b/log/level.go deleted file mode 100644 index 03adaa9..0000000 --- a/log/level.go +++ /dev/null @@ -1,58 +0,0 @@ -package log - -import ( - "fmt" - "strings" -) - -var AllLevels = []Level{ - PanicLevel, - FatalLevel, - ErrorLevel, - WarnLevel, - InfoLevel, - DebugLevel, - TraceLevel, -} - -const ( - DefaultLevel = Level("") - PanicLevel = Level("panic") - FatalLevel = Level("fatal") - ErrorLevel = Level("error") - WarnLevel = Level("warn") - InfoLevel = Level("info") - DebugLevel = Level("debug") - TraceLevel = Level("trace") -) - -type Level string - -func (instance *Level) Set(plain string) error { - plain = strings.ToLower(plain) - for _, candidate := range AllLevels { - if candidate.String() == plain { - *instance = candidate - return nil - } - } - - switch plain { - case "warning": - *instance = WarnLevel - return nil - case "", "default": - *instance = DefaultLevel - return nil - } - - allStr := make([]string, len(AllLevels)) - for i, v := range AllLevels { - allStr[i] = v.String() - } - return fmt.Errorf("illegal log level '%s' (possible values are: %s)", plain, strings.Join(allStr, ",")) -} - -func (instance Level) String() string { - return string(instance) -} diff --git a/log/logger.go b/log/logger.go deleted file mode 100644 index 2ce1308..0000000 --- a/log/logger.go +++ /dev/null @@ -1,170 +0,0 @@ -package log - -import ( - "bytes" - "encoding/json" - "github.com/sirupsen/logrus" -) - -var Default = NewDefault() - -func NewDefault() RootLogger { - instance := &LogrusLogger{ - Delegate: logrus.New(), - } - if err := instance.SetConfiguration(Configuration{}); err != nil { - panic(err) - } - return instance -} - -type Logger interface { - WithField(key string, value interface{}) Logger - WithDeepField(key string, value interface{}) Logger - WithDeepFieldOn(key string, value interface{}, on func() bool) Logger - WithError(err error) Logger - - Trace(what ...interface{}) - Debug(what ...interface{}) - Info(what ...interface{}) - Warn(what ...interface{}) - Error(what ...interface{}) - Fatal(what ...interface{}) - - Tracef(msg string, args ...interface{}) - Debugf(msg string, args ...interface{}) - Infof(msg string, args ...interface{}) - Warnf(msg string, args ...interface{}) - Errorf(msg string, args ...interface{}) - Fatalf(msg string, args ...interface{}) - - IsTraceEnabled() bool - IsDebugEnabled() bool - IsInfoEnabled() bool - IsWarnEnabled() bool - IsErrorEnabled() bool - IsFatalEnabled() bool -} - -type RootLogger interface { - Logger - - SetConfiguration(Configuration) error - GetConfiguration() Configuration -} - -func WithField(key string, value interface{}) Logger { - return Default.WithField(key, value) -} - -func WithDeepField(key string, value interface{}) Logger { - return Default.WithDeepField(key, value) -} - -func WithDeepFieldOn(key string, value interface{}, on func() bool) Logger { - return Default.WithDeepFieldOn(key, value, on) -} - -func WithError(err error) Logger { - return Default.WithError(err) -} - -func Trace(what ...interface{}) { - Default.Trace(what...) -} - -func Debug(what ...interface{}) { - Default.Debug(what...) -} - -func Info(what ...interface{}) { - Default.Info(what...) -} - -func Warn(what ...interface{}) { - Default.Warn(what...) -} - -func Error(what ...interface{}) { - Default.Error(what...) -} - -func Fatal(what ...interface{}) { - Default.Fatal(what...) -} - -func Tracef(msg string, args ...interface{}) { - Default.Tracef(msg, args...) -} - -func Debugf(msg string, args ...interface{}) { - Default.Debugf(msg, args...) -} - -func Infof(msg string, args ...interface{}) { - Default.Infof(msg, args...) -} - -func Warnf(msg string, args ...interface{}) { - Default.Warnf(msg, args...) -} - -func Errorf(msg string, args ...interface{}) { - Default.Errorf(msg, args...) -} - -func Fatalf(msg string, args ...interface{}) { - Default.Fatalf(msg, args...) -} - -func IsTraceEnabled() bool { - return Default.IsTraceEnabled() -} - -func IsDebugEnabled() bool { - return Default.IsDebugEnabled() -} - -func IsInfoEnabled() bool { - return Default.IsInfoEnabled() -} - -func IsWarnEnabled() bool { - return Default.IsWarnEnabled() -} - -func IsErrorEnabled() bool { - return Default.IsErrorEnabled() -} - -func IsFatalEnabled() bool { - return Default.IsFatalEnabled() -} - -type JsonValue struct { - Value interface{} - PrettyPrint bool -} - -func (instance JsonValue) String() string { - buf := new(bytes.Buffer) - encoder := json.NewEncoder(buf) - if instance.PrettyPrint { - encoder.SetIndent("", " ") - } - if err := encoder.Encode(instance.Value); err != nil { - panic(err) - } - return buf.String() -} - -type HasLogger interface { - Log() Logger -} - -func OrDefault(in Logger) Logger { - if in == nil { - return Default - } - return in -} diff --git a/log/logrus.go b/log/logrus.go deleted file mode 100644 index 6749fde..0000000 --- a/log/logrus.go +++ /dev/null @@ -1,282 +0,0 @@ -package log - -import ( - "fmt" - "github.com/sirupsen/logrus" - "reflect" -) - -type LogrusLogger struct { - configuration Configuration - - Delegate *logrus.Logger - EntryLoggerFactory func(*logrus.Logger) Logger -} - -func (instance *LogrusLogger) CreateEntryLogger() Logger { - if instance.EntryLoggerFactory == nil { - return &LogrusEntry{ - Root: instance, - Delegate: logrus.NewEntry(instance.Delegate), - } - } - return instance.EntryLoggerFactory(instance.Delegate) -} - -func (instance *LogrusLogger) WithField(key string, value interface{}) Logger { - return instance.CreateEntryLogger().WithField(key, value) -} - -func (instance *LogrusLogger) WithDeepField(key string, value interface{}) Logger { - return instance.CreateEntryLogger().WithDeepField(key, value) -} - -func (instance *LogrusLogger) WithDeepFieldOn(key string, value interface{}, on func() bool) Logger { - return instance.CreateEntryLogger().WithDeepFieldOn(key, value, on) -} - -func (instance *LogrusLogger) WithError(err error) Logger { - return instance.CreateEntryLogger().WithError(err) -} - -func (instance *LogrusLogger) Trace(what ...interface{}) { - instance.CreateEntryLogger().Trace(what...) -} - -func (instance *LogrusLogger) Debug(what ...interface{}) { - instance.CreateEntryLogger().Debug(what...) -} - -func (instance *LogrusLogger) Info(what ...interface{}) { - instance.CreateEntryLogger().Info(what...) -} - -func (instance *LogrusLogger) Warn(what ...interface{}) { - instance.CreateEntryLogger().Warn(what...) -} - -func (instance *LogrusLogger) Error(what ...interface{}) { - instance.CreateEntryLogger().Error(what...) -} - -func (instance *LogrusLogger) Fatal(what ...interface{}) { - instance.CreateEntryLogger().Fatal(what...) -} -func (instance *LogrusLogger) Tracef(msg string, args ...interface{}) { - instance.CreateEntryLogger().Tracef(msg, args...) -} - -func (instance *LogrusLogger) Debugf(msg string, args ...interface{}) { - instance.CreateEntryLogger().Debugf(msg, args...) -} - -func (instance *LogrusLogger) Infof(msg string, args ...interface{}) { - instance.CreateEntryLogger().Infof(msg, args...) -} - -func (instance *LogrusLogger) Warnf(msg string, args ...interface{}) { - instance.CreateEntryLogger().Warnf(msg, args...) -} - -func (instance *LogrusLogger) Errorf(msg string, args ...interface{}) { - instance.CreateEntryLogger().Errorf(msg, args...) -} - -func (instance *LogrusLogger) Fatalf(msg string, args ...interface{}) { - instance.CreateEntryLogger().Fatalf(msg, args...) -} - -func (instance *LogrusLogger) IsTraceEnabled() bool { - return instance.Delegate.Level >= logrus.TraceLevel -} - -func (instance *LogrusLogger) IsDebugEnabled() bool { - return instance.Delegate.Level >= logrus.DebugLevel -} - -func (instance *LogrusLogger) IsInfoEnabled() bool { - return instance.Delegate.Level >= logrus.InfoLevel -} - -func (instance *LogrusLogger) IsWarnEnabled() bool { - return instance.Delegate.Level >= logrus.WarnLevel -} - -func (instance *LogrusLogger) IsErrorEnabled() bool { - return instance.Delegate.Level >= logrus.ErrorLevel -} - -func (instance *LogrusLogger) IsFatalEnabled() bool { - return instance.Delegate.Level >= logrus.FatalLevel -} - -func (instance *LogrusLogger) SetConfiguration(configuration Configuration) error { - lvl, err := logrus.ParseLevel(configuration.GetLevel(InfoLevel).String()) - if err != nil { - return err - } - - var formatter logrus.Formatter - switch configuration.GetFormat(TextFormat) { - case JsonFormat: - formatter = &logrus.JSONFormatter{FieldMap: logrus.FieldMap{ - logrus.FieldKeyTime: "@timestamp", - logrus.FieldKeyLevel: "@level", - logrus.FieldKeyMsg: "@message", - logrus.FieldKeyFunc: "@caller", - }} - default: - formatter = &logrus.TextFormatter{ - FullTimestamp: true, - QuoteEmptyFields: true, - } - switch configuration.GetColorMode(AutoColorMode) { - case AlwaysColorMode: - formatter.(*logrus.TextFormatter).ForceColors = true - case NeverColorMode: - formatter.(*logrus.TextFormatter).DisableColors = true - } - } - - instance.Delegate.Level = lvl - instance.Delegate.Formatter = formatter - instance.Delegate.ReportCaller = configuration.ReportCaller - return nil -} - -func (instance LogrusLogger) GetConfiguration() Configuration { - return instance.configuration -} - -type LogrusEntry struct { - Root *LogrusLogger - Delegate *logrus.Entry -} - -func (instance *LogrusEntry) WithField(key string, value interface{}) Logger { - return &LogrusEntry{ - Root: instance.Root, - Delegate: instance.Delegate.WithField(key, value), - } -} - -func (instance *LogrusEntry) WithDeepField(key string, value interface{}) Logger { - return instance.WithField(key, JsonValue{ - Value: value, - }) -} - -func (instance *LogrusEntry) WithDeepFieldOn(key string, value interface{}, on func() bool) Logger { - if on() { - return instance.WithDeepField(key, value) - } - return instance -} - -func (instance *LogrusEntry) WithError(err error) Logger { - return &LogrusEntry{ - Root: instance.Root, - Delegate: instance.Delegate.WithError(err), - } -} - -type skipArgType struct { - val uint16 -} - -var skipArg = skipArgType{666} - -func (instance *LogrusEntry) evalArg(what interface{}) interface{} { - v := reflect.Indirect(reflect.ValueOf(what)) - t := v.Type() - if t.Kind() == reflect.Map { - for _, key := range v.MapKeys() { - sKey := fmt.Sprint(key.Interface()) - instance.Delegate.Data[sKey] = v.MapIndex(key).Interface() - } - return skipArg - } - return what -} - -func (instance *LogrusEntry) evalArgs(what []interface{}) []interface{} { - var result []interface{} - for _, arg := range what { - arg = instance.evalArg(arg) - if arg != skipArg { - result = append(result, arg) - } - } - return result -} - -func (instance *LogrusEntry) Trace(what ...interface{}) { - instance.Delegate.Trace(instance.evalArgs(what)...) -} - -func (instance *LogrusEntry) Debug(what ...interface{}) { - instance.Delegate.Debug(instance.evalArgs(what)...) -} - -func (instance *LogrusEntry) Info(what ...interface{}) { - instance.Delegate.Info(instance.evalArgs(what)...) -} - -func (instance *LogrusEntry) Warn(what ...interface{}) { - instance.Delegate.Warn(instance.evalArgs(what)...) -} - -func (instance *LogrusEntry) Error(what ...interface{}) { - instance.Delegate.Error(instance.evalArgs(what)...) -} - -func (instance *LogrusEntry) Fatal(what ...interface{}) { - instance.Delegate.Fatal(instance.evalArgs(what)...) -} -func (instance *LogrusEntry) Tracef(msg string, args ...interface{}) { - instance.Delegate.Tracef(msg, args...) -} - -func (instance *LogrusEntry) Debugf(msg string, args ...interface{}) { - instance.Delegate.Debugf(msg, args...) -} - -func (instance *LogrusEntry) Infof(msg string, args ...interface{}) { - instance.Delegate.Infof(msg, args...) -} - -func (instance *LogrusEntry) Warnf(msg string, args ...interface{}) { - instance.Delegate.Warnf(msg, args...) -} - -func (instance *LogrusEntry) Errorf(msg string, args ...interface{}) { - instance.Delegate.Errorf(msg, args...) -} - -func (instance *LogrusEntry) Fatalf(msg string, args ...interface{}) { - instance.Delegate.Fatalf(msg, args...) -} - -func (instance *LogrusEntry) IsTraceEnabled() bool { - return instance.Root.IsTraceEnabled() -} - -func (instance *LogrusEntry) IsDebugEnabled() bool { - return instance.Root.IsDebugEnabled() -} - -func (instance *LogrusEntry) IsInfoEnabled() bool { - return instance.Root.IsInfoEnabled() -} - -func (instance *LogrusEntry) IsWarnEnabled() bool { - return instance.Root.IsWarnEnabled() -} - -func (instance *LogrusEntry) IsErrorEnabled() bool { - return instance.Root.IsErrorEnabled() -} - -func (instance *LogrusEntry) IsFatalEnabled() bool { - return instance.Root.IsFatalEnabled() -} diff --git a/main/catCommand.go b/main/catCommand.go index 8f98be0..bd16874 100644 --- a/main/catCommand.go +++ b/main/catCommand.go @@ -3,7 +3,7 @@ package main import ( "github.com/echocat/goxr/box/packed" "github.com/echocat/goxr/common" - "github.com/echocat/goxr/log" + "github.com/echocat/slf4g" "github.com/urfave/cli" "io" "os" @@ -42,15 +42,16 @@ func (instance *CatCommand) NewCliCommands() []cli.Command { func (instance *CatCommand) ExecuteFromCli(_ *cli.Context) error { return instance.DoWithBox(func(box *packed.Box) error { - l := log.WithField("box", instance.Filename) + l := log.With("box", instance.Filename) l. - WithField("name", box.Name). - WithField("description", box.Description). - WithField("version", box.Version). - WithField("revision", box.Revision). - WithField("built", box.Built). - WithField("builtBy", box.BuiltBy). + With("name", box.Name). + With("description", box.Description). + With("version", box.Version). + With("revision", box.Revision). + With("built", box.Built). + With("builtBy", box.BuiltBy). + With("file", instance.Filename). Infof("Displaying of %s...", instance.Filename) return box.ForEach(instance.FilePredicate, func(info common.FileInfo) error { diff --git a/main/createCommand.go b/main/createCommand.go index 0f1f65d..d8126ae 100644 --- a/main/createCommand.go +++ b/main/createCommand.go @@ -2,7 +2,7 @@ package main import ( "github.com/echocat/goxr/box/packed" - "github.com/echocat/goxr/log" + "github.com/echocat/slf4g" "github.com/urfave/cli" ) @@ -70,22 +70,22 @@ func (instance *CreateCommand) ExecuteFromCli(ctx *cli.Context) error { return instance.DoWithWriter(func(writer *packed.Writer, bases []string) error { box := writer.Box() l := log. - WithField("box", instance.Filename) + With("box", instance.Filename) l. - WithField("name", box.Name). - WithField("description", box.Description). - WithField("version", box.Version). - WithField("revision", box.Revision). - WithField("built", box.Built). + With("name", box.Name). + With("description", box.Description). + With("version", box.Version). + With("revision", box.Revision). + With("built", box.Built). Infof("Creating box %s...", instance.Filename) for _, base := range bases { - sl := l.WithField("base", base) + sl := l.With("base", base) sl.Infof("Adding files of %s...", base) if err := writer.WriteFilesRecursive(base, func(candidate *packed.WriteCandidate) error { sl. - WithField("target", candidate.Target.Filename). - WithField("source", candidate.SourceFilename). + With("target", candidate.Target.Filename). + With("source", candidate.SourceFilename). Infof(" %s", candidate.Target.Filename) return nil }); err != nil { diff --git a/main/createServerCommand.go b/main/createServerCommand.go index 1353c9c..284db2e 100644 --- a/main/createServerCommand.go +++ b/main/createServerCommand.go @@ -4,8 +4,8 @@ import ( "bytes" "fmt" "github.com/echocat/goxr/box/packed" - "github.com/echocat/goxr/log" "github.com/echocat/goxr/runtime" + "github.com/echocat/slf4g" "github.com/urfave/cli" "io" "net/http" @@ -92,29 +92,29 @@ func (instance *CreateServerCommand) CliFlags() []cli.Flag { ) } -func (instance *CreateServerCommand) ExecuteFromCli(ctx *cli.Context) error { +func (instance *CreateServerCommand) ExecuteFromCli(*cli.Context) error { if err := instance.createServerStub(instance.Filename); err != nil { return err } return instance.DoWithWriter(func(writer *packed.Writer, bases []string) error { box := writer.Box() l := log. - WithField("box", instance.Filename) + With("box", instance.Filename) l. - WithField("name", box.Name). - WithField("description", box.Description). - WithField("version", box.Version). - WithField("revision", box.Revision). - WithField("built", box.Built). + With("name", box.Name). + With("description", box.Description). + With("version", box.Version). + With("revision", box.Revision). + With("built", box.Built). Infof("Creating server %s...", instance.Filename) for _, base := range bases { - sl := l.WithField("base", base) + sl := l.With("base", base) sl.Infof("Adding files of %s...", base) if err := writer.WriteFilesRecursive(base, func(candidate *packed.WriteCandidate) error { sl. - WithField("target", candidate.Target.Filename). - WithField("source", candidate.SourceFilename). + With("target", candidate.Target.Filename). + With("source", candidate.SourceFilename). Infof(" %s", candidate.Target.Filename) return nil }); err != nil { diff --git a/main/listCommand.go b/main/listCommand.go index 09c08c9..7c023fa 100644 --- a/main/listCommand.go +++ b/main/listCommand.go @@ -3,7 +3,7 @@ package main import ( "github.com/echocat/goxr/box/packed" "github.com/echocat/goxr/common" - "github.com/echocat/goxr/log" + "github.com/echocat/slf4g" "github.com/urfave/cli" "regexp" "time" @@ -41,14 +41,14 @@ func (instance *ListCommand) NewCliCommands() []cli.Command { func (instance *ListCommand) ExecuteFromCli(*cli.Context) error { return instance.DoWithBox(func(box *packed.Box) error { - l := log.WithField("box", instance.Filename) + l := log.With("box", instance.Filename) l. - WithField("name", box.Name). - WithField("description", box.Description). - WithField("version", box.Version). - WithField("revision", box.Revision). - WithField("built", box.Built). - WithField("builtBy", box.BuiltBy). + With("name", box.Name). + With("description", box.Description). + With("version", box.Version). + With("revision", box.Revision). + With("built", box.Built). + With("builtBy", box.BuiltBy). Infof("Entries of %s...", instance.Filename) return box.ForEach(instance.FilePredicate, func(info common.FileInfo) error { diff --git a/main/main.go b/main/main.go index 28635e5..19073e0 100644 --- a/main/main.go +++ b/main/main.go @@ -2,7 +2,8 @@ package main import ( "github.com/echocat/goxr/common" - "github.com/echocat/goxr/log" + "github.com/echocat/slf4g/native" + "github.com/echocat/slf4g/native/facade/value" "github.com/urfave/cli" ) @@ -17,16 +18,32 @@ func main() { app.Commands = append(app.Commands, ListCommandInstance.NewCliCommands()...) app.Commands = append(app.Commands, TruncateCommandInstance.NewCliCommands()...) - lc := log.Configuration{} - app.Flags = append(app.Flags, lc.Flags()...) + lv := value.NewProvider(native.DefaultProvider) + app.Flags = append(app.Flags, + cli.GenericFlag{ + Name: "logLevel", + Usage: "Specifies the minimum required log level.", + EnvVar: "GOXR_LOG_LEVEL", + Value: &lv.Level, + }, + cli.GenericFlag{ + Name: "logFormat", + Usage: "Specifies format output (text or json).", + EnvVar: "GOXR_LOG_FORMAT", + Value: &lv.Consumer.Formatter, + }, + cli.GenericFlag{ + Name: "logColorMode", + Usage: "Specifies if the output is in colors or not (auto, never or always).", + EnvVar: "GOXR_COLOR_MODE", + Value: lv.Consumer.Formatter.ColorMode, + }, + ) oldBefore := app.Before app.Before = func(context *cli.Context) error { if err := oldBefore(context); err != nil { return err } - if err := log.Default.SetConfiguration(lc); err != nil { - return err - } return nil } diff --git a/server/configuration/logging.go b/server/configuration/logging.go index d1377fd..35c741a 100644 --- a/server/configuration/logging.go +++ b/server/configuration/logging.go @@ -2,13 +2,11 @@ package configuration import ( "github.com/echocat/goxr" - "github.com/echocat/goxr/log" "github.com/urfave/cli" ) type Logging struct { - log.Configuration `yaml:",inline"` - AccessLog *bool `yaml:"accessLog,omitempty"` + AccessLog *bool `yaml:"accessLog,omitempty"` } func (instance Logging) GetAccessLog() bool { @@ -19,15 +17,13 @@ func (instance Logging) GetAccessLog() bool { return *r } -func (instance *Logging) Validate(_ goxr.Box) (errors []error) { +func (instance *Logging) Validate(goxr.Box) (errors []error) { return } func (instance Logging) Merge(with Logging) Logging { result := instance - result.Configuration = result.Configuration.Merge(with.Configuration) - if with.AccessLog != nil { result.AccessLog = &(*with.AccessLog) } @@ -36,5 +32,5 @@ func (instance Logging) Merge(with Logging) Logging { } func (instance *Logging) Flags() []cli.Flag { - return instance.Configuration.Flags() + return []cli.Flag{} } diff --git a/server/initiator.go b/server/initiator.go index aa5317f..09d5da2 100644 --- a/server/initiator.go +++ b/server/initiator.go @@ -6,9 +6,9 @@ import ( "github.com/echocat/goxr/box/fs" "github.com/echocat/goxr/box/packed" "github.com/echocat/goxr/common" - "github.com/echocat/goxr/log" "github.com/echocat/goxr/runtime" "github.com/echocat/goxr/server/configuration" + "github.com/echocat/slf4g" "github.com/urfave/cli" "os" ) @@ -26,7 +26,7 @@ type Initiator struct { func NewInitiatorFor(app *cli.App) *Initiator { result := &Initiator{ Server: &Server{ - Logger: log.NewDefault(), + Logger: log.GetLogger("server"), }, App: app, @@ -123,7 +123,7 @@ func InitiatorConfigureCliAction(instance *Initiator) error { return nil } -//noinspection GoSnakeCaseUsage +// noinspection GoSnakeCaseUsage func default_Initiator_Fail(_ *Initiator, err error) { ie := InitiatorErrorFor(err) common.MustWritef(os.Stderr, "%v\n\n", ie.Cause) diff --git a/server/main/main.go b/server/main/main.go index 6cf11ec..c663aff 100644 --- a/server/main/main.go +++ b/server/main/main.go @@ -3,11 +3,36 @@ package main import ( "github.com/echocat/goxr/common" "github.com/echocat/goxr/server" + "github.com/echocat/slf4g/native" + "github.com/echocat/slf4g/native/facade/value" + "github.com/urfave/cli" ) func main() { app := common.NewApp() + lv := value.NewProvider(native.DefaultProvider) + app.Flags = append(app.Flags, + cli.GenericFlag{ + Name: "logLevel", + Usage: "Specifies the minimum required log level.", + EnvVar: "GOXR_LOG_LEVEL", + Value: &lv.Level, + }, + cli.GenericFlag{ + Name: "logFormat", + Usage: "Specifies format output (text or json).", + EnvVar: "GOXR_LOG_FORMAT", + Value: &lv.Consumer.Formatter, + }, + cli.GenericFlag{ + Name: "logColorMode", + Usage: "Specifies if the output is in colors or not (auto, never or always).", + EnvVar: "GOXR_COLOR_MODE", + Value: lv.Consumer.Formatter.ColorMode, + }, + ) + initiator := server.NewInitiatorFor(app) initiator.Execute() diff --git a/server/response.go b/server/response.go index 16676ef..db738fb 100644 --- a/server/response.go +++ b/server/response.go @@ -3,7 +3,7 @@ package server import ( "bufio" "encoding/json" - "github.com/echocat/goxr/log" + "github.com/echocat/slf4g" "github.com/valyala/fasthttp" "net/http" "time" diff --git a/server/server.go b/server/server.go index d78796a..2ed2757 100644 --- a/server/server.go +++ b/server/server.go @@ -4,8 +4,8 @@ import ( "fmt" "github.com/echocat/goxr" "github.com/echocat/goxr/common" - "github.com/echocat/goxr/log" "github.com/echocat/goxr/server/configuration" + "github.com/echocat/slf4g" "github.com/valyala/fasthttp" "mime" "net/http" @@ -34,10 +34,10 @@ func (instance *Server) Run() error { s.Handler = fasthttp.CompressHandler(s.Handler) } address := instance.Configuration.Listen.GetHttpAddress() - instance.Log().Debug(map[string]interface{}{ - "event": "httpListenAndServe", - "address": address, - }) + instance.Log(). + With("event", "httpListenAndServe"). + With("address", address). + Debug() return s.ListenAndServe(address) } } @@ -68,7 +68,7 @@ func (instance *Server) Handle(ctx *fasthttp.RequestCtx) { "userAgent": string(ctx.Request.Header.UserAgent()), } if handled := instance.onAccessLog(boxToUse, ctxToUse, &entry); !handled { - instance.Log().Info(entry) + instance.Log().WithAll(entry).Info() } }(start) } @@ -237,7 +237,10 @@ func (instance *Server) ShouldHandleStatusCode(box goxr.Box, code int, ctx *fast } func (instance *Server) Log() log.Logger { - return log.OrDefault(instance.Logger) + if v := instance.Logger; v != nil { + return v + } + return log.GetRootLogger() } func (instance *Server) configure() error { @@ -247,11 +250,6 @@ func (instance *Server) configure() error { if err := instance.configureMimeTypes(); err != nil { return err } - if rl, ok := instance.Log().(log.RootLogger); ok { - if err := rl.SetConfiguration(instance.Configuration.Logging.Configuration); err != nil { - return err - } - } return nil } diff --git a/server/utils.go b/server/utils.go index 3e0b33a..e1bd9eb 100644 --- a/server/utils.go +++ b/server/utils.go @@ -2,7 +2,7 @@ package server import ( "github.com/echocat/goxr" - "github.com/echocat/goxr/log" + "github.com/echocat/slf4g" "github.com/valyala/fasthttp" "net/http" ) @@ -33,11 +33,11 @@ func BodyAllowedForStatus(status int) bool { func ReportNotHandableProblem(err error, ctx *fasthttp.RequestCtx, logger log.Logger) { logger. - WithField("remote", ctx.RemoteAddr().String()). - WithField("local", ctx.LocalAddr().String()). - WithField("host", string(ctx.Host())). - WithField("uri", string(ctx.RequestURI())). - WithField("errorType", "notHandable"). + With("remote", ctx.RemoteAddr().String()). + With("local", ctx.LocalAddr().String()). + With("host", string(ctx.Host())). + With("uri", string(ctx.RequestURI())). + With("errorType", "notHandable"). WithError(err). Warn() }