Browse Source

update zap/logrus hanler

pull/1/head
andrey1s 3 years ago
parent
commit
a8f5213750
  1. 90
      handler/logrus/logger.go
  2. 2
      handler/logrus/logger_test.go
  3. 94
      handler/zap/logger.go
  4. 2
      handler/zap/logger_test.go
  5. 27
      logger_example_logrus_test.go
  6. 27
      logger_example_zap_test.go
  7. 12
      writter.go

90
handler/logrus/logger.go

@ -9,82 +9,34 @@ import (
"gitoa.ru/go-4devs/log/level" "gitoa.ru/go-4devs/log/level"
) )
// Option configure logger. // Standard create new standart logrus handler.
type Option func(*logger) func Standard() log.Logger {
return New(logrus.StandardLogger())
// WithLevel sets callback level to log level.
func WithLevel(level level.Level, c func(*logrus.Entry, string)) Option {
return func(l *logger) {
l.levels[level] = c
}
}
// WithLogrus sets logrus logger.
func WithLogrus(logrus *logrus.Logger) Option {
return func(l *logger) {
l.logrus = logrus
}
} }
// New create new logrus handler. // New create new logrus handler.
func New(opts ...Option) log.Logger { func New(log *logrus.Logger) log.Logger {
log := logger{ return func(ctx context.Context, e *entry.Entry) (int, error) {
logrus: logrus.StandardLogger(),
levels: map[level.Level]func(*logrus.Entry, string){
level.Emergency: panicLog,
level.Alert: fatalLog,
level.Critical: errorLog,
level.Error: errorLog,
level.Warning: warnLog,
level.Notice: infoLog,
level.Info: infoLog,
level.Debug: debugLog,
},
}
for _, o := range opts {
o(&log)
}
return log.log
}
type logger struct {
levels map[level.Level]func(l *logrus.Entry, msg string)
logrus *logrus.Logger
}
func (l *logger) log(ctx context.Context, e *entry.Entry) (int, error) {
lrgFields := make(logrus.Fields, e.Fields().Len()) lrgFields := make(logrus.Fields, e.Fields().Len())
for _, field := range e.Fields() { for _, field := range e.Fields() {
lrgFields[string(field.Key())] = field.AsInterface() lrgFields[string(field.Key())] = field.AsInterface()
} }
write := log.WithContext(ctx).WithFields(lrgFields)
l.levels[e.Level()](l.logrus.WithFields(lrgFields), e.Message()) switch e.Level() {
case level.Emergency:
write.Panic(e.Message())
case level.Alert:
write.Fatal(e.Message())
case level.Critical, level.Error:
write.Error(e.Message())
case level.Warning:
write.Warn(e.Message())
case level.Notice, level.Info:
write.Info(e.Message())
case level.Debug:
write.Debug(e.Message())
}
return 0, nil return 0, nil
} }
func panicLog(e *logrus.Entry, msg string) {
e.Panic(msg)
}
func fatalLog(e *logrus.Entry, msg string) {
e.Fatal(msg)
}
func errorLog(e *logrus.Entry, msg string) {
e.Error(msg)
}
func warnLog(e *logrus.Entry, msg string) {
e.Warn(msg)
}
func infoLog(e *logrus.Entry, msg string) {
e.Info(msg)
}
func debugLog(e *logrus.Entry, msg string) {
e.Debug(msg)
} }

2
handler/logrus/logger_test.go

@ -23,7 +23,7 @@ func TestNew(t *testing.T) {
DisableTimestamp: true, DisableTimestamp: true,
}) })
handler := logrus.New(logrus.WithLogrus(lgrus)) handler := logrus.New(lgrus)
expect := "level=info msg=\"handle logrus message\"\n" expect := "level=info msg=\"handle logrus message\"\n"
if _, err := handler(ctx, entry.New(entry.WithLevel(level.Info), entry.WithMessage("handle logrus message"))); err != nil { if _, err := handler(ctx, entry.New(entry.WithLevel(level.Info), entry.WithMessage("handle logrus message"))); err != nil {

94
handler/zap/logger.go

@ -9,87 +9,55 @@ import (
"go.uber.org/zap" "go.uber.org/zap"
) )
// Option configure logger. func Nop() log.Logger {
type Option func(*logger) return New(zap.NewNop())
// WithLevel sets level logged message.
func WithLevel(level level.Level, f func(z *zap.Logger, msg string, fields ...zap.Field)) Option {
return func(l *logger) {
l.levels[level] = f
}
} }
// WithZap sets zap logger. func Example(options ...zap.Option) log.Logger {
func WithZap(z *zap.Logger) Option { return New(zap.NewExample(options...))
return func(l *logger) {
l.zap = z
}
} }
// New create handler by zap logger. func Production(options ...zap.Option) log.Logger {
func New(opts ...Option) log.Logger { z, err := zap.NewProduction(options...)
z, err := zap.NewDevelopment()
if err != nil { if err != nil {
panic(err) panic(err)
} }
log := logger{ return New(z)
zap: z, }
levels: map[level.Level]func(z *zap.Logger, msg string, fields ...zap.Field){
level.Emergency: fatalLog,
level.Alert: panicLog,
level.Critical: errorLog,
level.Error: errorLog,
level.Warning: warnLog,
level.Notice: infoLog,
level.Info: infoLog,
level.Debug: debugLog,
},
}
for _, opt := range opts { func Development(options ...zap.Option) log.Logger {
opt(&log) z, err := zap.NewDevelopment(options...)
if err != nil {
panic(err)
} }
return log.log return New(z)
}
type logger struct {
zap *zap.Logger
levels map[level.Level]func(z *zap.Logger, msg string, fields ...zap.Field)
} }
func (l *logger) log(ctx context.Context, e *entry.Entry) (int, error) { // New create handler by zap logger.
func New(z *zap.Logger) log.Logger {
return func(ctx context.Context, e *entry.Entry) (int, error) {
zf := make([]zap.Field, e.Fields().Len()) zf := make([]zap.Field, e.Fields().Len())
for i, field := range e.Fields() { for i, field := range e.Fields() {
zf[i] = zap.Any(string(field.Key()), field.AsInterface()) zf[i] = zap.Any(string(field.Key()), field.AsInterface())
} }
l.levels[e.Level()](l.zap, e.Message(), zf...) switch e.Level() {
case level.Emergency:
z.Fatal(e.Message(), zf...)
case level.Alert:
z.Panic(e.Message(), zf...)
case level.Critical, level.Error:
z.Error(e.Message(), zf...)
case level.Warning:
z.Warn(e.Message(), zf...)
case level.Notice, level.Info:
z.Info(e.Message(), zf...)
case level.Debug:
z.Debug(e.Message(), zf...)
}
return 0, nil return 0, nil
} }
func panicLog(z *zap.Logger, msg string, fields ...zap.Field) {
z.Panic(msg, fields...)
}
func fatalLog(z *zap.Logger, msg string, fields ...zap.Field) {
z.Fatal(msg, fields...)
}
func errorLog(z *zap.Logger, msg string, fields ...zap.Field) {
z.Error(msg, fields...)
}
func warnLog(z *zap.Logger, msg string, fields ...zap.Field) {
z.Warn(msg, fields...)
}
func infoLog(z *zap.Logger, msg string, fields ...zap.Field) {
z.Info(msg, fields...)
}
func debugLog(z *zap.Logger, msg string, fields ...zap.Field) {
z.Debug(msg, fields...)
} }

2
handler/zap/logger_test.go

@ -24,7 +24,7 @@ func TestNew(t *testing.T) {
EncodeTime: zapcore.ISO8601TimeEncoder, EncodeTime: zapcore.ISO8601TimeEncoder,
EncodeDuration: zapcore.StringDurationEncoder, EncodeDuration: zapcore.StringDurationEncoder,
}), zapcore.AddSync(buf), zapcore.DebugLevel) }), zapcore.AddSync(buf), zapcore.DebugLevel)
logger := zlog.New(zlog.WithZap(zap.New(core))) logger := zlog.New(zap.New(core))
expect := `{"level":"info","msg":"handle zap message","env":"test"}` + "\n" expect := `{"level":"info","msg":"handle zap message","env":"test"}` + "\n"
if _, err := logger(ctx, entry.New( if _, err := logger(ctx, entry.New(

27
logger_example_logrus_test.go

@ -2,20 +2,27 @@ package log_test
import ( import (
"io" "io"
"os"
slogrus "github.com/sirupsen/logrus"
"gitoa.ru/go-4devs/log/field" "gitoa.ru/go-4devs/log/field"
"gitoa.ru/go-4devs/log/handler/zap" "gitoa.ru/go-4devs/log/handler/logrus"
uzap "go.uber.org/zap"
) )
func ExampleNew_zapHandler() { func ExampleNew_logrusHandler() {
log := zap.New(zap.WithZap(uzap.NewExample())) lgrs := slogrus.New()
log.Err(ctx, "log zap") lgrs.SetOutput(os.Stdout)
log.ErrKV(ctx, "log zap kv", field.Int("int", 42)) lgrs.SetFormatter(&slogrus.TextFormatter{
log.ErrKVs(ctx, "log zap kv sugar", "err", io.EOF) DisableTimestamp: true,
})
log := logrus.New(lgrs)
log.Err(ctx, "log logrus")
log.ErrKV(ctx, "log logrus kv", field.Int("int", 42))
log.ErrKVs(ctx, "log logrus kv sugar", "err", io.EOF)
// Output: // Output:
// {"level":"error","msg":"log zap"} // level=error msg="log logrus"
// {"level":"error","msg":"log zap kv","int":42} // level=error msg="log logrus kv" int=42
// {"level":"error","msg":"log zap kv sugar","err":"EOF"} // level=error msg="log logrus kv sugar" err=EOF
} }

27
logger_example_zap_test.go

@ -2,27 +2,20 @@ package log_test
import ( import (
"io" "io"
"os"
slogrus "github.com/sirupsen/logrus"
"gitoa.ru/go-4devs/log/field" "gitoa.ru/go-4devs/log/field"
"gitoa.ru/go-4devs/log/handler/logrus" "gitoa.ru/go-4devs/log/handler/zap"
uzap "go.uber.org/zap"
) )
func ExampleNew_logrusHandler() { func ExampleNew_zapHandler() {
lgrs := slogrus.New() log := zap.New(uzap.NewExample())
lgrs.SetOutput(os.Stdout) log.Err(ctx, "log zap")
lgrs.SetFormatter(&slogrus.TextFormatter{ log.ErrKV(ctx, "log zap kv", field.Int("int", 42))
DisableTimestamp: true, log.ErrKVs(ctx, "log zap kv sugar", "err", io.EOF)
})
log := logrus.New(logrus.WithLogrus(lgrs))
log.Err(ctx, "log logrus")
log.ErrKV(ctx, "log logrus kv", field.Int("int", 42))
log.ErrKVs(ctx, "log logrus kv sugar", "err", io.EOF)
// Output: // Output:
// level=error msg="log logrus" // {"level":"error","msg":"log zap"}
// level=error msg="log logrus kv" int=42 // {"level":"error","msg":"log zap kv","int":42}
// level=error msg="log logrus kv sugar" err=EOF // {"level":"error","msg":"log zap kv sugar","err":"EOF"}
} }

12
writter.go

@ -50,9 +50,7 @@ func WithWriter(writer io.Writer) Option {
// WithStdout sets logged to os.Stdout. // WithStdout sets logged to os.Stdout.
func WithStdout() Option { func WithStdout() Option {
return func(l *log) { return WithWriter(os.Stdout)
l.w = os.Stdout
}
} }
// WithEncode sets format log. // WithEncode sets format log.
@ -64,16 +62,12 @@ func WithEncode(e Encode) Option {
// WithStringFormat sets format as simple string. // WithStringFormat sets format as simple string.
func WithStringFormat() Option { func WithStringFormat() Option {
return func(l *log) { return WithEncode(stringFormat())
l.e = stringFormat()
}
} }
// WithJSONFormat sets json output format. // WithJSONFormat sets json output format.
func WithJSONFormat() Option { func WithJSONFormat() Option {
return func(l *log) { return WithEncode(jsonFormat)
l.e = jsonFormat
}
} }
func stringFormat() func(entry *entry.Entry) ([]byte, error) { func stringFormat() func(entry *entry.Entry) ([]byte, error) {

Loading…
Cancel
Save