Skip to content

Commit

Permalink
Merge pull request x-cray#25 from teo/master
Browse files Browse the repository at this point in the history
Add support for PrefixPadding.
  • Loading branch information
cjbassi committed Dec 16, 2018
2 parents bb2702d + d4c78d9 commit e9c19a7
Showing 1 changed file with 18 additions and 2 deletions.
20 changes: 18 additions & 2 deletions formatter.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,11 @@ type TextFormatter struct {
// Its default value is zero, which means no padding will be applied for msg.
SpacePadding int

// Pad prefix field with spaces on the right for display.
// The value for this parameter will be the size of padding.
// Its default value is zero, which means no padding will be applied for prefix.
PrefixPadding int

// Color scheme to use.
colorScheme *compiledColorScheme

Expand Down Expand Up @@ -253,14 +258,25 @@ func (f *TextFormatter) printColored(b *bytes.Buffer, entry *logrus.Entry, keys
prefix := ""
message := entry.Message

adjustedPrefixPadding := f.PrefixPadding //compensate for ANSI color sequences

if prefixValue, ok := entry.Data["prefix"]; ok {
rawPrefixLength := len(prefixValue.(string))
prefix = colorScheme.PrefixColor(" " + prefixValue.(string) + ":")
adjustedPrefixPadding = f.PrefixPadding + (len(prefix) - rawPrefixLength - 1)
} else {
prefixValue, trimmedMsg := extractPrefix(entry.Message)
rawPrefixLength := len(prefixValue)
if len(prefixValue) > 0 {
prefix = colorScheme.PrefixColor(" " + prefixValue + ":")
message = trimmedMsg
}
adjustedPrefixPadding = f.PrefixPadding + (len(prefix) - rawPrefixLength - 1)
}

prefixFormat := "%s"
if f.PrefixPadding != 0 {
prefixFormat = fmt.Sprintf("%%-%ds", adjustedPrefixPadding)
}

messageFormat := "%s"
Expand All @@ -269,15 +285,15 @@ func (f *TextFormatter) printColored(b *bytes.Buffer, entry *logrus.Entry, keys
}

if f.DisableTimestamp {
fmt.Fprintf(b, "%s%s "+messageFormat, level, prefix, message)
fmt.Fprintf(b, "%s"+ prefixFormat + " " + messageFormat, level, prefix, message)
} else {
var timestamp string
if !f.FullTimestamp {
timestamp = fmt.Sprintf("[%04d]", miniTS())
} else {
timestamp = fmt.Sprintf("[%s]", entry.Time.Format(timestampFormat))
}
fmt.Fprintf(b, "%s %s%s "+messageFormat, colorScheme.TimestampColor(timestamp), level, prefix, message)
fmt.Fprintf(b, "%s %s" + prefixFormat + " " + messageFormat, colorScheme.TimestampColor(timestamp), level, prefix, message)
}
for _, k := range keys {
if k != "prefix" {
Expand Down

0 comments on commit e9c19a7

Please sign in to comment.