From 0b16df555c1006e2689a7b9104c512101b32d8c1 Mon Sep 17 00:00:00 2001 From: Denis Arh Date: Sun, 25 Aug 2019 12:43:35 +0200 Subject: [PATCH] Add ability to log masked (string) values --- pkg/logger/masked.go | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 pkg/logger/masked.go diff --git a/pkg/logger/masked.go b/pkg/logger/masked.go new file mode 100644 index 000000000..911e1881c --- /dev/null +++ b/pkg/logger/masked.go @@ -0,0 +1,39 @@ +package logger + +import ( + "fmt" + "strings" + + "go.uber.org/zap" + "go.uber.org/zap/zapcore" +) + +// Mask is a passthrough for MaskIf +func Mask(key string, val interface{}) zap.Field { + return MaskIf(key, val, true) +} + +// MaskIf conditionally masks (replaces string with * of equal length input string/stringer +func MaskIf(key string, val interface{}, mask bool) zap.Field { + var str string + + switch v := val.(type) { + case fmt.Stringer: + str = v.String() + case string: + str = v + default: + // empty string for other types + str = "" + } + + if mask { + str = strings.Repeat("*", len(str)) + } + + return zap.Field{ + Key: key, + Type: zapcore.StringType, + String: str, + } +}