Skip to content

Commit

Permalink
Add custom filter for text_formatter (#212)
Browse files Browse the repository at this point in the history
* Add custom filter for text_formatter

In order to make console output more user friendly, lets remove some fields that are unnecessary for human consumption (team, component, service)

* remove run_id as well
  • Loading branch information
edznux-dd authored Jul 1, 2024
1 parent b8baea2 commit d6331d8
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
6 changes: 4 additions & 2 deletions pkg/telemetry/log/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,8 @@ func Trace(ctx context.Context, opts ...LoggerOption) *KubehoundLogger {
}

func GetLogrusFormatter() logrus.Formatter {
customTextFormatter := NewFilteredTextFormatter(DefaultRemovedFields)

switch logFormat := os.Getenv("KH_LOG_FORMAT"); {
// Datadog require the logged field to be "message" and not "msg"
case logFormat == "dd":
Expand All @@ -138,8 +140,8 @@ func GetLogrusFormatter() logrus.Formatter {
case logFormat == "json":
return &logrus.JSONFormatter{}
case logFormat == "text":
return &logrus.TextFormatter{}
return customTextFormatter
default:
return &logrus.TextFormatter{}
return customTextFormatter
}
}
36 changes: 36 additions & 0 deletions pkg/telemetry/log/text_formatter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package log

import (
"time"

logrus "github.com/sirupsen/logrus"
)

var (
DefaultRemovedFields = []string{"component", "team", "service", "run_id"}
)

// FilteredTextFormatter is a logrus.TextFormatter that filters out some specific fields that are not needed for humans.
// These fields are usually more helpful for machines, and with json formatting for example.
type FilteredTextFormatter struct {
tf logrus.TextFormatter
removedFields []string
}

func NewFilteredTextFormatter(removedFields []string) logrus.Formatter {
return &FilteredTextFormatter{
tf: logrus.TextFormatter{
FullTimestamp: true,
TimestampFormat: time.TimeOnly,
},
removedFields: removedFields,
}
}

func (f *FilteredTextFormatter) Format(entry *logrus.Entry) ([]byte, error) {
for _, field := range f.removedFields {
delete(entry.Data, field)
}

return f.tf.Format(entry)
}

0 comments on commit d6331d8

Please sign in to comment.