http urls monitor.

text_formatter.go 4.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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. // FieldMap allows users to customize the names of keys for default fields.
  50. // As an example:
  51. // formatter := &TextFormatter{
  52. // FieldMap: FieldMap{
  53. // FieldKeyTime: "@timestamp",
  54. // FieldKeyLevel: "@level",
  55. // FieldKeyMsg: "@message"}}
  56. FieldMap FieldMap
  57. sync.Once
  58. }
  59. func (f *TextFormatter) init(entry *Entry) {
  60. if entry.Logger != nil {
  61. f.isTerminal = checkIfTerminal(entry.Logger.Out)
  62. }
  63. }
  64. // Format renders a single log entry
  65. func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
  66. prefixFieldClashes(entry.Data, f.FieldMap)
  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. var b *bytes.Buffer
  75. if entry.Buffer != nil {
  76. b = entry.Buffer
  77. } else {
  78. b = &bytes.Buffer{}
  79. }
  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, f.FieldMap.resolve(FieldKeyTime), entry.Time.Format(timestampFormat))
  91. }
  92. f.appendKeyValue(b, f.FieldMap.resolve(FieldKeyLevel), entry.Level.String())
  93. if entry.Message != "" {
  94. f.appendKeyValue(b, f.FieldMap.resolve(FieldKeyMsg), 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())
  116. if !f.DisableLevelTruncation {
  117. levelText = levelText[0:4]
  118. }
  119. if f.DisableTimestamp {
  120. fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m %-44s ", levelColor, levelText, entry.Message)
  121. } else if !f.FullTimestamp {
  122. fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d] %-44s ", levelColor, levelText, int(entry.Time.Sub(baseTimestamp)/time.Second), entry.Message)
  123. } else {
  124. fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), entry.Message)
  125. }
  126. for _, k := range keys {
  127. v := entry.Data[k]
  128. fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=", levelColor, k)
  129. f.appendValue(b, v)
  130. }
  131. }
  132. func (f *TextFormatter) needsQuoting(text string) bool {
  133. if f.QuoteEmptyFields && len(text) == 0 {
  134. return true
  135. }
  136. for _, ch := range text {
  137. if !((ch >= 'a' && ch <= 'z') ||
  138. (ch >= 'A' && ch <= 'Z') ||
  139. (ch >= '0' && ch <= '9') ||
  140. ch == '-' || ch == '.' || ch == '_' || ch == '/' || ch == '@' || ch == '^' || ch == '+') {
  141. return true
  142. }
  143. }
  144. return false
  145. }
  146. func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) {
  147. if b.Len() > 0 {
  148. b.WriteByte(' ')
  149. }
  150. b.WriteString(key)
  151. b.WriteByte('=')
  152. f.appendValue(b, value)
  153. }
  154. func (f *TextFormatter) appendValue(b *bytes.Buffer, value interface{}) {
  155. stringVal, ok := value.(string)
  156. if !ok {
  157. stringVal = fmt.Sprint(value)
  158. }
  159. if !f.needsQuoting(stringVal) {
  160. b.WriteString(stringVal)
  161. } else {
  162. b.WriteString(fmt.Sprintf("%q", stringVal))
  163. }
  164. }