diff options
author | Valery Piashchynski <[email protected]> | 2020-12-21 19:42:23 +0300 |
---|---|---|
committer | Valery Piashchynski <[email protected]> | 2020-12-21 19:42:23 +0300 |
commit | ee8b4075c0f836d698d1ae505c87c17147de447a (patch) | |
tree | 531d980e5bfb94ee39b03952a97e0445f7955409 /plugins/logger | |
parent | 0ad45031047bb479e06ce0a0f496c6db9b2641c9 (diff) |
Move plugins to the roadrunner-plugins repository
Diffstat (limited to 'plugins/logger')
-rw-r--r-- | plugins/logger/config.go | 94 | ||||
-rw-r--r-- | plugins/logger/encoder.go | 66 | ||||
-rw-r--r-- | plugins/logger/plugin.go | 65 | ||||
-rw-r--r-- | plugins/logger/tests/.rr.yaml | 3 | ||||
-rw-r--r-- | plugins/logger/tests/logger_test.go | 74 | ||||
-rw-r--r-- | plugins/logger/tests/plugin.go | 40 | ||||
-rw-r--r-- | plugins/logger/zap_adapter.go | 57 |
7 files changed, 0 insertions, 399 deletions
diff --git a/plugins/logger/config.go b/plugins/logger/config.go deleted file mode 100644 index f7a5742c..00000000 --- a/plugins/logger/config.go +++ /dev/null @@ -1,94 +0,0 @@ -package logger - -import ( - "strings" - - "go.uber.org/zap" - "go.uber.org/zap/zapcore" -) - -// ChannelConfig configures loggers per channel. -type ChannelConfig struct { - // Dedicated channels per logger. By default logger allocated via named logger. - Channels map[string]Config `json:"channels" yaml:"channels"` -} - -type Config struct { - // Mode configures logger based on some default template (development, production, off). - Mode string `json:"mode" yaml:"mode"` - - // Level is the minimum enabled logging level. Note that this is a dynamic - // level, so calling ChannelConfig.Level.SetLevel will atomically change the log - // level of all loggers descended from this config. - Level string `json:"level" yaml:"level"` - - // Encoding sets the logger's encoding. Valid values are "json" and - // "console", as well as any third-party encodings registered via - // RegisterEncoder. - Encoding string `json:"encoding" yaml:"encoding"` - - // Output is a list of URLs or file paths to write logging output to. - // See Open for details. - Output []string `json:"output" yaml:"output"` - - // ErrorOutput is a list of URLs to write internal logger errors to. - // The default is standard error. - // - // Note that this setting only affects internal errors; for sample code that - // sends error-level logs to a different location from info- and debug-level - // logs, see the package-level AdvancedConfiguration example. - ErrorOutput []string `json:"errorOutput" yaml:"errorOutput"` -} - -// ZapConfig converts config into Zap configuration. -func (cfg *Config) BuildLogger() (*zap.Logger, error) { - var zCfg zap.Config - switch strings.ToLower(cfg.Mode) { - case "off", "none": - return zap.NewNop(), nil - case "production": - zCfg = zap.NewProductionConfig() - case "development": - zCfg = zap.NewDevelopmentConfig() - default: - zCfg = zap.Config{ - Level: zap.NewAtomicLevelAt(zap.DebugLevel), - Encoding: "console", - EncoderConfig: zapcore.EncoderConfig{ - MessageKey: "message", - LevelKey: "level", - TimeKey: "time", - NameKey: "name", - EncodeName: ColoredHashedNameEncoder, - EncodeLevel: ColoredLevelEncoder, - EncodeTime: UTCTimeEncoder, - EncodeCaller: zapcore.ShortCallerEncoder, - }, - OutputPaths: []string{"stderr"}, - ErrorOutputPaths: []string{"stderr"}, - } - } - - if cfg.Level != "" { - level := zap.NewAtomicLevel() - if err := level.UnmarshalText([]byte(cfg.Level)); err == nil { - zCfg.Level = level - } - } - - if cfg.Encoding != "" { - zCfg.Encoding = cfg.Encoding - } - - if len(cfg.Output) != 0 { - zCfg.OutputPaths = cfg.Output - } - - if len(cfg.ErrorOutput) != 0 { - zCfg.ErrorOutputPaths = cfg.ErrorOutput - } - - // todo: https://github.com/uber-go/zap/blob/master/FAQ.md#does-zap-support-log-rotation - - return zCfg.Build() -} diff --git a/plugins/logger/encoder.go b/plugins/logger/encoder.go deleted file mode 100644 index 4ff583c4..00000000 --- a/plugins/logger/encoder.go +++ /dev/null @@ -1,66 +0,0 @@ -package logger - -import ( - "hash/fnv" - "strings" - "time" - - "github.com/fatih/color" - "go.uber.org/zap/zapcore" -) - -var colorMap = []func(string, ...interface{}) string{ - color.HiYellowString, - color.HiGreenString, - color.HiBlueString, - color.HiRedString, - color.HiCyanString, - color.HiMagentaString, -} - -// ColoredLevelEncoder colorizes log levels. -func ColoredLevelEncoder(level zapcore.Level, enc zapcore.PrimitiveArrayEncoder) { - switch level { - case zapcore.DebugLevel: - enc.AppendString(color.HiWhiteString(level.CapitalString())) - case zapcore.InfoLevel: - enc.AppendString(color.HiCyanString(level.CapitalString())) - case zapcore.WarnLevel: - enc.AppendString(color.HiYellowString(level.CapitalString())) - case zapcore.ErrorLevel, zapcore.DPanicLevel: - enc.AppendString(color.HiRedString(level.CapitalString())) - case zapcore.PanicLevel, zapcore.FatalLevel: - enc.AppendString(color.HiMagentaString(level.CapitalString())) - } -} - -// ColoredNameEncoder colorizes service names. -func ColoredNameEncoder(s string, enc zapcore.PrimitiveArrayEncoder) { - if len(s) < 12 { - s += strings.Repeat(" ", 12-len(s)) - } - - enc.AppendString(color.HiGreenString(s)) -} - -// ColoredHashedNameEncoder colorizes service names and assigns different colors to different names. -func ColoredHashedNameEncoder(s string, enc zapcore.PrimitiveArrayEncoder) { - if len(s) < 12 { - s += strings.Repeat(" ", 12-len(s)) - } - - colorID := stringHash(s, len(colorMap)) - enc.AppendString(colorMap[colorID](s)) -} - -// UTCTimeEncoder encodes time into short UTC specific timestamp. -func UTCTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) { - enc.AppendString(t.UTC().Format("2006/01/02 15:04:05")) -} - -// returns string hash -func stringHash(name string, base int) int { - h := fnv.New32a() - _, _ = h.Write([]byte(name)) - return int(h.Sum32()) % base -} diff --git a/plugins/logger/plugin.go b/plugins/logger/plugin.go deleted file mode 100644 index cdd67482..00000000 --- a/plugins/logger/plugin.go +++ /dev/null @@ -1,65 +0,0 @@ -package logger - -import ( - "github.com/spiral/endure" - "github.com/spiral/roadrunner/v2/interfaces/config" - "github.com/spiral/roadrunner/v2/interfaces/log" - "go.uber.org/zap" -) - -// PluginName declares plugin name. -const PluginName = "logs" - -// ZapLogger manages zap logger. -type ZapLogger struct { - base *zap.Logger - cfg Config - channels ChannelConfig -} - -// Init logger service. -func (z *ZapLogger) Init(cfg config.Configurer) error { - err := cfg.UnmarshalKey(PluginName, &z.cfg) - if err != nil { - return err - } - - err = cfg.UnmarshalKey(PluginName, &z.channels) - if err != nil { - return err - } - - z.base, err = z.cfg.BuildLogger() - return err -} - -// DefaultLogger returns default logger. -func (z *ZapLogger) DefaultLogger() (log.Logger, error) { - return NewZapAdapter(z.base), nil -} - -// NamedLogger returns logger dedicated to the specific channel. Similar to Named() but also reads the core params. -func (z *ZapLogger) NamedLogger(name string) (log.Logger, error) { - if cfg, ok := z.channels.Channels[name]; ok { - l, err := cfg.BuildLogger() - if err != nil { - return nil, err - } - return NewZapAdapter(l), nil - } - - return NewZapAdapter(z.base.Named(name)), nil -} - -// NamedLogger returns logger dedicated to the specific channel. Similar to Named() but also reads the core params. -func (z *ZapLogger) ServiceLogger(n endure.Named) (log.Logger, error) { - return z.NamedLogger(n.Name()) -} - -// Provides declares factory methods. -func (z *ZapLogger) Provides() []interface{} { - return []interface{}{ - z.ServiceLogger, - z.DefaultLogger, - } -} diff --git a/plugins/logger/tests/.rr.yaml b/plugins/logger/tests/.rr.yaml deleted file mode 100644 index cb555ec3..00000000 --- a/plugins/logger/tests/.rr.yaml +++ /dev/null @@ -1,3 +0,0 @@ -logs: - mode: development - level: debug
\ No newline at end of file diff --git a/plugins/logger/tests/logger_test.go b/plugins/logger/tests/logger_test.go deleted file mode 100644 index 3e6faf1f..00000000 --- a/plugins/logger/tests/logger_test.go +++ /dev/null @@ -1,74 +0,0 @@ -package tests - -import ( - "os" - "os/signal" - "testing" - "time" - - "github.com/spiral/endure" - "github.com/spiral/roadrunner/v2/plugins/config" - "github.com/spiral/roadrunner/v2/plugins/logger" - "github.com/stretchr/testify/assert" -) - -func TestLogger(t *testing.T) { - container, err := endure.NewContainer(nil, endure.RetryOnFail(true), endure.SetLogLevel(endure.ErrorLevel)) - if err != nil { - t.Fatal(err) - } - // config plugin - vp := &config.Viper{} - vp.Path = ".rr.yaml" - vp.Prefix = "rr" - err = container.Register(vp) - if err != nil { - t.Fatal(err) - } - - err = container.Register(&Plugin{}) - if err != nil { - t.Fatal(err) - } - - err = container.Register(&logger.ZapLogger{}) - if err != nil { - t.Fatal(err) - } - - err = container.Init() - if err != nil { - t.Fatal(err) - } - - errCh, err := container.Serve() - if err != nil { - t.Fatal(err) - } - - // stop by CTRL+C - c := make(chan os.Signal, 1) - signal.Notify(c, os.Interrupt) - - // stop after 10 seconds - tt := time.NewTicker(time.Second * 10) - - for { - select { - case e := <-errCh: - assert.NoError(t, e.Error) - assert.NoError(t, container.Stop()) - return - case <-c: - er := container.Stop() - if er != nil { - panic(er) - } - return - case <-tt.C: - tt.Stop() - assert.NoError(t, container.Stop()) - return - } - } -} diff --git a/plugins/logger/tests/plugin.go b/plugins/logger/tests/plugin.go deleted file mode 100644 index 37c5c5f2..00000000 --- a/plugins/logger/tests/plugin.go +++ /dev/null @@ -1,40 +0,0 @@ -package tests - -import ( - "github.com/spiral/errors" - "github.com/spiral/roadrunner/v2/interfaces/config" - "github.com/spiral/roadrunner/v2/interfaces/log" -) - -type Plugin struct { - config config.Configurer - log log.Logger -} - -func (p1 *Plugin) Init(cfg config.Configurer, log log.Logger) error { - p1.config = cfg - p1.log = log - return nil -} - -func (p1 *Plugin) Serve() chan error { - errCh := make(chan error, 1) - p1.log.Error("error", "test", errors.E(errors.Str("test"))) - p1.log.Info("error", "test", errors.E(errors.Str("test"))) - p1.log.Debug("error", "test", errors.E(errors.Str("test"))) - p1.log.Warn("error", "test", errors.E(errors.Str("test"))) - - p1.log.Error("error", "test") - p1.log.Info("error", "test") - p1.log.Debug("error", "test") - p1.log.Warn("error", "test") - return errCh -} - -func (p1 *Plugin) Stop() error { - return nil -} - -func (p1 *Plugin) Name() string { - return "logger_plugin" -} diff --git a/plugins/logger/zap_adapter.go b/plugins/logger/zap_adapter.go deleted file mode 100644 index 41e6d8f9..00000000 --- a/plugins/logger/zap_adapter.go +++ /dev/null @@ -1,57 +0,0 @@ -package logger - -import ( - "fmt" - - "github.com/spiral/roadrunner/v2/interfaces/log" - "go.uber.org/zap" -) - -type ZapAdapter struct { - zl *zap.Logger -} - -// Create NewZapAdapter which uses general log interface -func NewZapAdapter(zapLogger *zap.Logger) *ZapAdapter { - return &ZapAdapter{ - zl: zapLogger.WithOptions(zap.AddCallerSkip(1)), - } -} - -func (log *ZapAdapter) fields(keyvals []interface{}) []zap.Field { - // we should have even number of keys and values - if len(keyvals)%2 != 0 { - return []zap.Field{zap.Error(fmt.Errorf("odd number of keyvals pairs: %v", keyvals))} - } - - var fields []zap.Field - for i := 0; i < len(keyvals); i += 2 { - key, ok := keyvals[i].(string) - if !ok { - key = fmt.Sprintf("%v", keyvals[i]) - } - fields = append(fields, zap.Any(key, keyvals[i+1])) - } - - return fields -} - -func (log *ZapAdapter) Debug(msg string, keyvals ...interface{}) { - log.zl.Debug(msg, log.fields(keyvals)...) -} - -func (log *ZapAdapter) Info(msg string, keyvals ...interface{}) { - log.zl.Info(msg, log.fields(keyvals)...) -} - -func (log *ZapAdapter) Warn(msg string, keyvals ...interface{}) { - log.zl.Warn(msg, log.fields(keyvals)...) -} - -func (log *ZapAdapter) Error(msg string, keyvals ...interface{}) { - log.zl.Error(msg, log.fields(keyvals)...) -} - -func (log *ZapAdapter) With(keyvals ...interface{}) log.Logger { - return NewZapAdapter(log.zl.With(log.fields(keyvals)...)) -} |