commit 844119673fee072236cdb557ecad5012dfdc8e61 Author: jar3b Date: Fri Jun 29 00:14:52 2018 +0300 Initial commit diff --git a/README.md b/README.md new file mode 100644 index 0000000..7b83dd6 --- /dev/null +++ b/README.md @@ -0,0 +1,11 @@ +# logrus-levelpad-formatter + +Logrus (https://github.com/sirupsen/logrus) formatter with messages like + +``` +[INFO]: 2006-01-02T15:04:05Z07:00 - Log message +``` + +Configure + +... \ No newline at end of file diff --git a/formatter.go b/formatter.go new file mode 100644 index 0000000..4f544b3 --- /dev/null +++ b/formatter.go @@ -0,0 +1,65 @@ +package levelpad + +import ( + "strings" + "time" + + "github.com/sirupsen/logrus" +) + +const ( + // Default log format will output [INFO]: 2006-01-02T15:04:05Z07:00 - Log message + defaultLogFormat = "[%lvl%]: %time% - %msg%" + defaultTimestampFormat = time.RFC3339 +) + +func padRight(str, pad string, length int) string { + for { + str += pad + if len(str) > length { + return str[0:length] + } + } +} + +// Formatter implements logrus.Formatter interface. +type Formatter struct { + // Timestamp format + TimestampFormat string + // Available standard keys: time, msg, lvl + // Also can include custom fields but limited to strings. + // All of fields need to be wrapped inside %% i.e %time% %msg% + LogFormat string + LevelPad int +} + +// Format building log message. +func (f *Formatter) Format(entry *logrus.Entry) ([]byte, error) { + output := f.LogFormat + if output == "" { + output = defaultLogFormat + } + + timestampFormat := f.TimestampFormat + if timestampFormat == "" { + timestampFormat = defaultTimestampFormat + } + + output = strings.Replace(output, "%time%", entry.Time.Format(timestampFormat), 1) + + output = strings.Replace(output, "%msg%", entry.Message, 1) + + level := strings.ToUpper(entry.Level.String()) + if f.LevelPad != 0 { + level = padRight(level, " ", f.LevelPad) + } + output = strings.Replace(output, "%lvl%", level, 1) + + for k, v := range entry.Data { + if s, ok := v.(string); ok { + output = strings.Replace(output, "%"+k+"%", s, 1) + } + } + + return []byte(output), nil +}