text_formatter.go 4.2 KB

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