text_formatter.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. package logrus
  2. import (
  3. "bytes"
  4. "fmt"
  5. "sort"
  6. "strings"
  7. "sync"
  8. "time"
  9. )
  10. const (
  11. nocolor = 0
  12. red = 31
  13. green = 32
  14. yellow = 33
  15. blue = 36
  16. gray = 37
  17. )
  18. var (
  19. baseTimestamp time.Time
  20. )
  21. func init() {
  22. baseTimestamp = time.Now()
  23. }
  24. type TextFormatter struct {
  25. // Set to true to bypass checking for a TTY before outputting colors.
  26. ForceColors bool
  27. // Force disabling colors.
  28. DisableColors bool
  29. // Disable timestamp logging. useful when output is redirected to logging
  30. // system that already adds timestamps.
  31. DisableTimestamp bool
  32. // Enable logging the full timestamp when a TTY is attached instead of just
  33. // the time passed since beginning of execution.
  34. FullTimestamp bool
  35. // TimestampFormat to use for display when a full timestamp is printed
  36. TimestampFormat string
  37. // The fields are sorted by default for a consistent output. For applications
  38. // that log extremely frequently and don't use the JSON formatter this may not
  39. // be desired.
  40. DisableSorting bool
  41. // QuoteEmptyFields will wrap empty fields in quotes if true
  42. QuoteEmptyFields bool
  43. // Whether the logger's out is to a terminal
  44. isTerminal bool
  45. sync.Once
  46. }
  47. func (f *TextFormatter) init(entry *Entry) {
  48. if entry.Logger != nil {
  49. f.isTerminal = IsTerminal(entry.Logger.Out)
  50. }
  51. }
  52. func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
  53. var b *bytes.Buffer
  54. keys := make([]string, 0, len(entry.Data))
  55. for k := range entry.Data {
  56. keys = append(keys, k)
  57. }
  58. if !f.DisableSorting {
  59. sort.Strings(keys)
  60. }
  61. if entry.Buffer != nil {
  62. b = entry.Buffer
  63. } else {
  64. b = &bytes.Buffer{}
  65. }
  66. prefixFieldClashes(entry.Data)
  67. f.Do(func() { f.init(entry) })
  68. isColored := (f.ForceColors || f.isTerminal) && !f.DisableColors
  69. timestampFormat := f.TimestampFormat
  70. if timestampFormat == "" {
  71. timestampFormat = DefaultTimestampFormat
  72. }
  73. if isColored {
  74. f.printColored(b, entry, keys, timestampFormat)
  75. } else {
  76. if !f.DisableTimestamp {
  77. f.appendKeyValue(b, "time", entry.Time.Format(timestampFormat))
  78. }
  79. f.appendKeyValue(b, "level", entry.Level.String())
  80. if entry.Message != "" {
  81. f.appendKeyValue(b, "msg", entry.Message)
  82. }
  83. for _, key := range keys {
  84. f.appendKeyValue(b, key, entry.Data[key])
  85. }
  86. }
  87. b.WriteByte('\n')
  88. return b.Bytes(), nil
  89. }
  90. func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string, timestampFormat string) {
  91. var levelColor int
  92. switch entry.Level {
  93. case DebugLevel:
  94. levelColor = gray
  95. case WarnLevel:
  96. levelColor = yellow
  97. case ErrorLevel, FatalLevel, PanicLevel:
  98. levelColor = red
  99. default:
  100. levelColor = blue
  101. }
  102. levelText := strings.ToUpper(entry.Level.String())[0:4]
  103. if f.DisableTimestamp {
  104. fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m %-44s ", levelColor, levelText, entry.Message)
  105. } else if !f.FullTimestamp {
  106. fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d] %-44s ", levelColor, levelText, int(entry.Time.Sub(baseTimestamp)/time.Second), entry.Message)
  107. } else {
  108. fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), entry.Message)
  109. }
  110. for _, k := range keys {
  111. v := entry.Data[k]
  112. fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=", levelColor, k)
  113. f.appendValue(b, v)
  114. }
  115. }
  116. func (f *TextFormatter) needsQuoting(text string) bool {
  117. if f.QuoteEmptyFields && len(text) == 0 {
  118. return true
  119. }
  120. for _, ch := range text {
  121. if !((ch >= 'a' && ch <= 'z') ||
  122. (ch >= 'A' && ch <= 'Z') ||
  123. (ch >= '0' && ch <= '9') ||
  124. ch == '-' || ch == '.' || ch == '_' || ch == '/' || ch == '@' || ch == '^' || ch == '+') {
  125. return true
  126. }
  127. }
  128. return false
  129. }
  130. func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) {
  131. b.WriteString(key)
  132. b.WriteByte('=')
  133. f.appendValue(b, value)
  134. b.WriteByte(' ')
  135. }
  136. func (f *TextFormatter) appendValue(b *bytes.Buffer, value interface{}) {
  137. stringVal, ok := value.(string)
  138. if !ok {
  139. stringVal = fmt.Sprint(value)
  140. }
  141. if !f.needsQuoting(stringVal) {
  142. b.WriteString(stringVal)
  143. } else {
  144. b.WriteString(fmt.Sprintf("%q", stringVal))
  145. }
  146. }