text_formatter.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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 = 34
  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. // QuoteCharacter can be set to the override the default quoting character "
  44. // with something else. For example: ', or `.
  45. QuoteCharacter string
  46. // Whether the logger's out is to a terminal
  47. isTerminal bool
  48. sync.Once
  49. }
  50. func (f *TextFormatter) init(entry *Entry) {
  51. if len(f.QuoteCharacter) == 0 {
  52. f.QuoteCharacter = "\""
  53. }
  54. if entry.Logger != nil {
  55. f.isTerminal = IsTerminal(entry.Logger.Out)
  56. }
  57. }
  58. func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
  59. var b *bytes.Buffer
  60. keys := make([]string, 0, len(entry.Data))
  61. for k := range entry.Data {
  62. keys = append(keys, k)
  63. }
  64. if !f.DisableSorting {
  65. sort.Strings(keys)
  66. }
  67. if entry.Buffer != nil {
  68. b = entry.Buffer
  69. } else {
  70. b = &bytes.Buffer{}
  71. }
  72. prefixFieldClashes(entry.Data)
  73. f.Do(func() { f.init(entry) })
  74. isColored := (f.ForceColors || f.isTerminal) && !f.DisableColors
  75. timestampFormat := f.TimestampFormat
  76. if timestampFormat == "" {
  77. timestampFormat = DefaultTimestampFormat
  78. }
  79. if isColored {
  80. f.printColored(b, entry, keys, timestampFormat)
  81. } else {
  82. if !f.DisableTimestamp {
  83. f.appendKeyValue(b, "time", entry.Time.Format(timestampFormat))
  84. }
  85. f.appendKeyValue(b, "level", entry.Level.String())
  86. if entry.Message != "" {
  87. f.appendKeyValue(b, "msg", entry.Message)
  88. }
  89. for _, key := range keys {
  90. f.appendKeyValue(b, key, entry.Data[key])
  91. }
  92. }
  93. b.WriteByte('\n')
  94. return b.Bytes(), nil
  95. }
  96. func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string, timestampFormat string) {
  97. var levelColor int
  98. switch entry.Level {
  99. case DebugLevel:
  100. levelColor = gray
  101. case WarnLevel:
  102. levelColor = yellow
  103. case ErrorLevel, FatalLevel, PanicLevel:
  104. levelColor = red
  105. default:
  106. levelColor = blue
  107. }
  108. levelText := strings.ToUpper(entry.Level.String())[0:4]
  109. if f.DisableTimestamp {
  110. fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m %-44s ", levelColor, levelText, entry.Message)
  111. } else if !f.FullTimestamp {
  112. fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d] %-44s ", levelColor, levelText, int(entry.Time.Sub(baseTimestamp)/time.Second), entry.Message)
  113. } else {
  114. fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), entry.Message)
  115. }
  116. for _, k := range keys {
  117. v := entry.Data[k]
  118. fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=", levelColor, k)
  119. f.appendValue(b, v)
  120. }
  121. }
  122. func (f *TextFormatter) needsQuoting(text string) bool {
  123. if f.QuoteEmptyFields && len(text) == 0 {
  124. return true
  125. }
  126. for _, ch := range text {
  127. if !((ch >= 'a' && ch <= 'z') ||
  128. (ch >= 'A' && ch <= 'Z') ||
  129. (ch >= '0' && ch <= '9') ||
  130. ch == '-' || ch == '.') {
  131. return true
  132. }
  133. }
  134. return false
  135. }
  136. func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) {
  137. b.WriteString(key)
  138. b.WriteByte('=')
  139. f.appendValue(b, value)
  140. b.WriteByte(' ')
  141. }
  142. func (f *TextFormatter) appendValue(b *bytes.Buffer, value interface{}) {
  143. switch value := value.(type) {
  144. case string:
  145. if !f.needsQuoting(value) {
  146. b.WriteString(value)
  147. } else {
  148. fmt.Fprintf(b, "%s%v%s", f.QuoteCharacter, value, f.QuoteCharacter)
  149. }
  150. case error:
  151. errmsg := value.Error()
  152. if !f.needsQuoting(errmsg) {
  153. b.WriteString(errmsg)
  154. } else {
  155. fmt.Fprintf(b, "%s%v%s", f.QuoteCharacter, errmsg, f.QuoteCharacter)
  156. }
  157. default:
  158. fmt.Fprint(b, value)
  159. }
  160. }