From 6cf7d92904e2eec21958fa26256c7d169db2af30 Mon Sep 17 00:00:00 2001 From: Vasiliy Tolstov Date: Tue, 22 Feb 2022 14:17:16 +0300 Subject: [PATCH] fix panic Signed-off-by: Vasiliy Tolstov --- zerolog.go | 13 ++++++------- zerolog_test.go | 9 ++++++++- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/zerolog.go b/zerolog.go index c164b09..02b3c81 100644 --- a/zerolog.go +++ b/zerolog.go @@ -126,7 +126,11 @@ func (l *zeroLogger) Init(opts ...logger.Option) error { if l.opts.Fields != nil { data := make(map[string]interface{}, len(l.opts.Fields)/2) for i := 0; i < len(l.opts.Fields); i += 2 { - data[l.opts.Fields[i].(string)] = l.opts.Fields[i+1] + fld, ok := l.opts.Fields[i].(string) + if !ok { + return fmt.Errorf("field type invalid %T not string", l.opts.Fields[i]) + } + data[fld] = l.opts.Fields[i+1] } l.zLog = l.zLog.With().Fields(data).Logger() } @@ -140,12 +144,7 @@ func (l *zeroLogger) Init(opts ...logger.Option) error { } func (l *zeroLogger) Fields(fields ...interface{}) logger.Logger { - data := make(map[string]interface{}, len(fields)/2) - for i := 0; i < len(fields); i += 2 { - data[fields[i].(string)] = fields[i+1] - } - l.zLog = l.zLog.With().Fields(data).Logger() - return l + return l.Clone(logger.WithFields(fields...)) } func (l *zeroLogger) V(level logger.Level) bool { diff --git a/zerolog_test.go b/zerolog_test.go index b897709..6b295c7 100644 --- a/zerolog_test.go +++ b/zerolog_test.go @@ -19,10 +19,17 @@ func TestFields(t *testing.T) { if err := l.Init(); err != nil { t.Fatal(err) } - l.Fields("key", "val").Infof(ctx, "message") + nl := l.Fields("key", "val") + nl.Infof(ctx, "message") if !bytes.Contains(buf.Bytes(), []byte(`"key":"val"`)) { t.Fatalf("logger fields not works, buf contains: %s", buf.Bytes()) } + buf.Reset() + mnl := l.Fields(map[string]interface{}{"key": "val"}) + mnl.Infof(ctx, "message") + if bytes.Contains(buf.Bytes(), []byte(`"key":"val"`)) { + t.Fatalf("logger fields not works, buf contains: %s", buf.Bytes()) + } } func TestOutput(t *testing.T) {