text_formatter.go 4.2 KB

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