/
LogTaggedStruct.go
75 lines (64 loc) · 2.25 KB
/
LogTaggedStruct.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package ulog
import (
"fmt"
"reflect"
"strings"
)
// Helper function to log out a struct annotated with "env", "mask" and "warnIf" annotations
// Good to use with the "github.com/codingconcepts/env" package
func LogEnvStruct(envStruct interface{}, prefix string) {
logTaggedStructWithMaskingAndWarning(envStruct, "env", "mask", "warnIf", prefix)
}
// Helper function to log out a struct annotated with "json", "mask" and "warnIf" annotations
// Good to use with the "encoding/json" package
func LogJSONStruct(envStruct interface{}, prefix string) {
logTaggedStructWithMaskingAndWarning(envStruct, "json", "mask", "warnIf", prefix)
}
func logTaggedStructWithMaskingAndWarning(taggedStruct interface{}, tag string, maskTag string, warnTag string, prefix string) {
// Dereference if needed
usedTaggedStruct := taggedStruct
if reflect.ValueOf(taggedStruct).Kind() == reflect.Ptr {
usedTaggedStruct = reflect.ValueOf(taggedStruct).Elem().Interface()
}
typeOf := reflect.TypeOf(usedTaggedStruct)
valueOf := reflect.ValueOf(usedTaggedStruct)
allWarnings := []string{}
allOutput := []string{}
for i := 0; i < valueOf.NumField(); i++ {
derefFieldVal := valueOf.Field(i)
derefFieldType := typeOf.Field(i)
tag := derefFieldType.Tag.Get(tag)
maskTag := derefFieldType.Tag.Get(maskTag)
warnTag := derefFieldType.Tag.Get(warnTag)
if tag != "" {
if maskTag != "" {
allOutput = append(allOutput, fmt.Sprintf("%s%s = %v", prefix, tag, "***"))
} else {
allOutput = append(allOutput, fmt.Sprintf("%s%s = %v", prefix, tag, getStringFromReflect(derefFieldVal)))
}
if warnTag == getStringFromReflect(valueOf.Field(i)) {
allWarnings = append(allWarnings, fmt.Sprintf("%s%s has warning value", prefix, tag))
}
}
}
if len(allWarnings) > 0 {
Warn("WARNINGS ..............................................................")
}
for _, warning := range allWarnings {
Warn(warning)
}
if len(allOutput) > 0 {
Info("Config ................................................................")
}
for _, output := range allOutput {
Info(output)
}
}
func getStringFromReflect(val reflect.Value) string {
switch val.Interface().(type) {
case string:
return strings.ReplaceAll(val.Interface().(string), "%", "%%")
default:
return fmt.Sprintf("%v", val)
}
}