text_formatter.go 3.6 KB

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