Add in preprocessing hook to add additional key/value pairs

This commit is contained in:
Jonathan Bartlett 2021-08-04 18:02:06 -05:00
parent b50299cfaa
commit 8b395d0834
2 changed files with 24 additions and 0 deletions

View File

@ -49,6 +49,8 @@ type JSONFormatter struct {
// }
FieldMap FieldMap
PreprocessorHook func(Fields)
// CallerPrettyfier can be set by the user to modify the content
// of the function and file keys in the json data when ReportCaller is
// activated. If any of the returned value is the empty string the
@ -108,6 +110,10 @@ func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
}
}
if f.PreprocessorHook != nil {
f.PreprocessorHook(data)
}
var b *bytes.Buffer
if entry.Buffer != nil {
b = entry.Buffer

View File

@ -370,3 +370,21 @@ func TestJSONEnableHTMLEscape(t *testing.T) {
t.Error("Message should be HTML escaped", s)
}
}
func TestPreprocessorHook(t *testing.T) {
formatter := &JSONFormatter{}
formatter.PreprocessorHook = func(f Fields) {
f["testme"] = "hello"
}
b, err := formatter.Format(&Entry{Message: "My Message"})
if err != nil {
t.Fatal("Unable to format entry: ", err)
}
s := string(b)
if !strings.Contains(s, `"testme"`) {
t.Error("Message should contain key added by preprocessor hook")
}
if !strings.Contains(s, `"hello"`) {
t.Error("Message should contain value added by preprocessor hook")
}
}