Skip to content

Commit b9ea828

Browse files
authored
Changed for for mapping fields, different var for logger in zap example (#581)
* Mapping Fields works correctly now * Logger instance used for logging is now being used only once, previous code has been rewriting instance, and then duplicating fields.
1 parent cb96b57 commit b9ea828

File tree

1 file changed

+20
-9
lines changed

1 file changed

+20
-9
lines changed

interceptors/logging/examples/zap/example_test.go

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,24 +17,35 @@ import (
1717
func InterceptorLogger(l *zap.Logger) logging.Logger {
1818
return logging.LoggerFunc(func(ctx context.Context, lvl logging.Level, msg string, fields ...any) {
1919
f := make([]zap.Field, 0, len(fields)/2)
20+
2021
for i := 0; i < len(fields); i += 2 {
21-
i := logging.Fields(fields).Iterator()
22-
if i.Next() {
23-
k, v := i.At()
24-
f = append(f, zap.Any(k, v))
22+
key := fields[i]
23+
value := fields[i+1]
24+
25+
switch v := value.(type) {
26+
case string:
27+
f = append(f, zap.String(key.(string), v))
28+
case int:
29+
f = append(f, zap.Int(key.(string), v))
30+
case bool:
31+
f = append(f, zap.Bool(key.(string), v))
32+
default:
33+
f = append(f, zap.Any(key.(string), v))
2534
}
2635
}
27-
l = l.WithOptions(zap.AddCallerSkip(1)).With(f...)
36+
37+
38+
logger = l.WithOptions(zap.AddCallerSkip(1)).With(f...)
2839

2940
switch lvl {
3041
case logging.LevelDebug:
31-
l.Debug(msg)
42+
logger.Debug(msg)
3243
case logging.LevelInfo:
33-
l.Info(msg)
44+
logger.Info(msg)
3445
case logging.LevelWarn:
35-
l.Warn(msg)
46+
logger.Warn(msg)
3647
case logging.LevelError:
37-
l.Error(msg)
48+
logger.Error(msg)
3849
default:
3950
panic(fmt.Sprintf("unknown level %v", lvl))
4051
}

0 commit comments

Comments
 (0)