Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add in preprocessing hook to add additional key/value pairs #1271

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions json_formatter.go
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
18 changes: 18 additions & 0 deletions json_formatter_test.go
Expand Up @@ -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")
}
}