Skip to content
This repository has been archived by the owner on Dec 11, 2022. It is now read-only.

Commit

Permalink
Merge incoming json with additional fields (#2)
Browse files Browse the repository at this point in the history
Allows ELK to parse original values as top level
json keys, not tucked under e.g. 'json: {}'
  • Loading branch information
aslakknutsen authored Sep 1, 2017
1 parent 93edbc5 commit 23fb4a0
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
7 changes: 6 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,5 +89,10 @@ func LogRaw(logger *log.Logger, fields map[string]interface{}, msg string) {
// LogJSON logs all application/json types with request body as fields in the field 'json'
func LogJSON(logger *log.Logger, fields map[string]interface{}, json map[string]interface{}) {
entry := log.NewEntry(logger)
entry.WithFields(fields).WithField("json", json).Info("")
msg := ""
if m, ok := json["msg"].(string); ok {
msg = m
delete(json, "msg")
}
entry.WithFields(fields).WithFields(json).Info(msg)
}
13 changes: 12 additions & 1 deletion main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,18 @@ func TestJSONOutput(t *testing.T) {
log, status := run(t, "application/json", "{\"a\":1}")
assert.Equal(t, http.StatusOK, status)

assert.Contains(t, log, "\"json\":{\"a\":1}")
assert.Contains(t, log, "{\"a\":1,")
assert.Contains(t, log, "test-ns")
assert.Contains(t, log, "test-ot")
assert.Contains(t, log, "test-on")
}

func TestJSONOutputMsgFromOriginal(t *testing.T) {
log, status := run(t, "application/json", "{\"msg\":\"a\"}")
assert.Equal(t, http.StatusOK, status)

assert.Contains(t, log, "\"msg\":\"a\",")
assert.NotContains(t, log, "\"fields.msg\"")
assert.Contains(t, log, "test-ns")
assert.Contains(t, log, "test-ot")
assert.Contains(t, log, "test-on")
Expand Down

0 comments on commit 23fb4a0

Please sign in to comment.