text_formatter.go 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  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 keys []string = make([]string, 0, len(entry.Data))
  49. for k := range entry.Data {
  50. keys = append(keys, k)
  51. }
  52. if !f.DisableSorting {
  53. sort.Strings(keys)
  54. }
  55. b := &bytes.Buffer{}
  56. prefixFieldClashes(entry.Data)
  57. isColorTerminal := isTerminal && (runtime.GOOS != "windows")
  58. isColored := (f.ForceColors || isColorTerminal) && !f.DisableColors
  59. timestampFormat := f.TimestampFormat
  60. if timestampFormat == "" {
  61. timestampFormat = DefaultTimestampFormat
  62. }
  63. if isColored {
  64. f.printColored(b, entry, keys, timestampFormat)
  65. } else {
  66. if !f.DisableTimestamp {
  67. f.appendKeyValue(b, "time", entry.Time.Format(timestampFormat))
  68. }
  69. f.appendKeyValue(b, "level", entry.Level.String())
  70. if entry.Message != "" {
  71. f.appendKeyValue(b, "msg", entry.Message)
  72. }
  73. for _, key := range keys {
  74. f.appendKeyValue(b, key, entry.Data[key])
  75. }
  76. }
  77. b.WriteByte('\n')
  78. return b.Bytes(), nil
  79. }
  80. func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string, timestampFormat string) {
  81. var levelColor int
  82. switch entry.Level {
  83. case DebugLevel:
  84. levelColor = gray
  85. case WarnLevel:
  86. levelColor = yellow
  87. case ErrorLevel, FatalLevel, PanicLevel:
  88. levelColor = red
  89. default:
  90. levelColor = blue
  91. }
  92. levelText := strings.ToUpper(entry.Level.String())[0:4]
  93. if !f.FullTimestamp {
  94. fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d] %-44s ", levelColor, levelText, miniTS(), entry.Message)
  95. } else {
  96. fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), entry.Message)
  97. }
  98. for _, k := range keys {
  99. v := entry.Data[k]
  100. fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=%+v", levelColor, k, v)
  101. }
  102. }
  103. func needsQuoting(text string) bool {
  104. for _, ch := range text {
  105. if !((ch >= 'a' && ch <= 'z') ||
  106. (ch >= 'A' && ch <= 'Z') ||
  107. (ch >= '0' && ch <= '9') ||
  108. ch == '-' || ch == '.') {
  109. return false
  110. }
  111. }
  112. return true
  113. }
  114. func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) {
  115. b.WriteString(key)
  116. b.WriteByte('=')
  117. switch value := value.(type) {
  118. case string:
  119. if needsQuoting(value) {
  120. b.WriteString(value)
  121. } else {
  122. fmt.Fprintf(b, "%q", value)
  123. }
  124. case error:
  125. errmsg := value.Error()
  126. if needsQuoting(errmsg) {
  127. b.WriteString(errmsg)
  128. } else {
  129. fmt.Fprintf(b, "%q", value)
  130. }
  131. default:
  132. fmt.Fprint(b, value)
  133. }
  134. b.WriteByte(' ')
  135. }