另客网go项目公用的代码库

text_formatter.go 6.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. package logrus
  2. import (
  3. "bytes"
  4. "fmt"
  5. "os"
  6. "runtime"
  7. "sort"
  8. "strings"
  9. "sync"
  10. "time"
  11. )
  12. const (
  13. nocolor = 0
  14. red = 31
  15. green = 32
  16. yellow = 33
  17. blue = 36
  18. gray = 37
  19. )
  20. var (
  21. baseTimestamp time.Time
  22. emptyFieldMap FieldMap
  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. // Override coloring based on CLICOLOR and CLICOLOR_FORCE. - https://bixense.com/clicolors/
  34. EnvironmentOverrideColors bool
  35. // Disable timestamp logging. useful when output is redirected to logging
  36. // system that already adds timestamps.
  37. DisableTimestamp bool
  38. // Enable logging the full timestamp when a TTY is attached instead of just
  39. // the time passed since beginning of execution.
  40. FullTimestamp bool
  41. // TimestampFormat to use for display when a full timestamp is printed
  42. TimestampFormat string
  43. // The fields are sorted by default for a consistent output. For applications
  44. // that log extremely frequently and don't use the JSON formatter this may not
  45. // be desired.
  46. DisableSorting bool
  47. // The keys sorting function, when uninitialized it uses sort.Strings.
  48. SortingFunc func([]string)
  49. // Disables the truncation of the level text to 4 characters.
  50. DisableLevelTruncation bool
  51. // QuoteEmptyFields will wrap empty fields in quotes if true
  52. QuoteEmptyFields bool
  53. // Whether the logger's out is to a terminal
  54. isTerminal bool
  55. // FieldMap allows users to customize the names of keys for default fields.
  56. // As an example:
  57. // formatter := &TextFormatter{
  58. // FieldMap: FieldMap{
  59. // FieldKeyTime: "@timestamp",
  60. // FieldKeyLevel: "@level",
  61. // FieldKeyMsg: "@message"}}
  62. FieldMap FieldMap
  63. terminalInitOnce sync.Once
  64. }
  65. func (f *TextFormatter) init(entry *Entry) {
  66. if entry.Logger != nil {
  67. f.isTerminal = checkIfTerminal(entry.Logger.Out)
  68. if f.isTerminal {
  69. initTerminal(entry.Logger.Out)
  70. }
  71. }
  72. }
  73. func (f *TextFormatter) isColored() bool {
  74. isColored := f.ForceColors || (f.isTerminal && (runtime.GOOS != "windows"))
  75. if f.EnvironmentOverrideColors {
  76. if force, ok := os.LookupEnv("CLICOLOR_FORCE"); ok && force != "0" {
  77. isColored = true
  78. } else if ok && force == "0" {
  79. isColored = false
  80. } else if os.Getenv("CLICOLOR") == "0" {
  81. isColored = false
  82. }
  83. }
  84. return isColored && !f.DisableColors
  85. }
  86. // Format renders a single log entry
  87. func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
  88. data := make(Fields)
  89. for k, v := range entry.Data {
  90. data[k] = v
  91. }
  92. prefixFieldClashes(data, f.FieldMap, entry.HasCaller())
  93. keys := make([]string, 0, len(data))
  94. for k := range data {
  95. keys = append(keys, k)
  96. }
  97. fixedKeys := make([]string, 0, 4+len(data))
  98. if !f.DisableTimestamp {
  99. fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyTime))
  100. }
  101. fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyLevel))
  102. if entry.Message != "" {
  103. fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyMsg))
  104. }
  105. if entry.err != "" {
  106. fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyLogrusError))
  107. }
  108. if entry.HasCaller() {
  109. fixedKeys = append(fixedKeys,
  110. f.FieldMap.resolve(FieldKeyFunc), f.FieldMap.resolve(FieldKeyFile))
  111. }
  112. if !f.DisableSorting {
  113. if f.SortingFunc == nil {
  114. sort.Strings(keys)
  115. fixedKeys = append(fixedKeys, keys...)
  116. } else {
  117. if !f.isColored() {
  118. fixedKeys = append(fixedKeys, keys...)
  119. f.SortingFunc(fixedKeys)
  120. } else {
  121. f.SortingFunc(keys)
  122. }
  123. }
  124. } else {
  125. fixedKeys = append(fixedKeys, keys...)
  126. }
  127. var b *bytes.Buffer
  128. if entry.Buffer != nil {
  129. b = entry.Buffer
  130. } else {
  131. b = &bytes.Buffer{}
  132. }
  133. f.terminalInitOnce.Do(func() { f.init(entry) })
  134. timestampFormat := f.TimestampFormat
  135. if timestampFormat == "" {
  136. timestampFormat = defaultTimestampFormat
  137. }
  138. if f.isColored() {
  139. f.printColored(b, entry, keys, data, timestampFormat)
  140. } else {
  141. for _, key := range fixedKeys {
  142. var value interface{}
  143. switch {
  144. case key == f.FieldMap.resolve(FieldKeyTime):
  145. value = entry.Time.Format(timestampFormat)
  146. case key == f.FieldMap.resolve(FieldKeyLevel):
  147. value = entry.Level.String()
  148. case key == f.FieldMap.resolve(FieldKeyMsg):
  149. value = entry.Message
  150. case key == f.FieldMap.resolve(FieldKeyLogrusError):
  151. value = entry.err
  152. case key == f.FieldMap.resolve(FieldKeyFunc) && entry.HasCaller():
  153. value = entry.Caller.Function
  154. case key == f.FieldMap.resolve(FieldKeyFile) && entry.HasCaller():
  155. value = fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line)
  156. default:
  157. value = data[key]
  158. }
  159. f.appendKeyValue(b, key, value)
  160. }
  161. }
  162. b.WriteByte('\n')
  163. return b.Bytes(), nil
  164. }
  165. func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string, data Fields, timestampFormat string) {
  166. var levelColor int
  167. switch entry.Level {
  168. case DebugLevel, TraceLevel:
  169. levelColor = gray
  170. case WarnLevel:
  171. levelColor = yellow
  172. case ErrorLevel, FatalLevel, PanicLevel:
  173. levelColor = red
  174. default:
  175. levelColor = blue
  176. }
  177. levelText := strings.ToUpper(entry.Level.String())
  178. if !f.DisableLevelTruncation {
  179. levelText = levelText[0:4]
  180. }
  181. // Remove a single newline if it already exists in the message to keep
  182. // the behavior of logrus text_formatter the same as the stdlib log package
  183. entry.Message = strings.TrimSuffix(entry.Message, "\n")
  184. caller := ""
  185. if entry.HasCaller() {
  186. caller = fmt.Sprintf("%s:%d %s()",
  187. entry.Caller.File, entry.Caller.Line, entry.Caller.Function)
  188. }
  189. if f.DisableTimestamp {
  190. fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m%s %-44s ", levelColor, levelText, caller, entry.Message)
  191. } else if !f.FullTimestamp {
  192. fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d]%s %-44s ", levelColor, levelText, int(entry.Time.Sub(baseTimestamp)/time.Second), caller, entry.Message)
  193. } else {
  194. fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s]%s %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), caller, entry.Message)
  195. }
  196. for _, k := range keys {
  197. v := data[k]
  198. fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=", levelColor, k)
  199. f.appendValue(b, v)
  200. }
  201. }
  202. func (f *TextFormatter) needsQuoting(text string) bool {
  203. if f.QuoteEmptyFields && len(text) == 0 {
  204. return true
  205. }
  206. for _, ch := range text {
  207. if !((ch >= 'a' && ch <= 'z') ||
  208. (ch >= 'A' && ch <= 'Z') ||
  209. (ch >= '0' && ch <= '9') ||
  210. ch == '-' || ch == '.' || ch == '_' || ch == '/' || ch == '@' || ch == '^' || ch == '+') {
  211. return true
  212. }
  213. }
  214. return false
  215. }
  216. func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) {
  217. if b.Len() > 0 {
  218. b.WriteByte(' ')
  219. }
  220. b.WriteString(key)
  221. b.WriteByte('=')
  222. f.appendValue(b, value)
  223. }
  224. func (f *TextFormatter) appendValue(b *bytes.Buffer, value interface{}) {
  225. stringVal, ok := value.(string)
  226. if !ok {
  227. stringVal = fmt.Sprint(value)
  228. }
  229. if !f.needsQuoting(stringVal) {
  230. b.WriteString(stringVal)
  231. } else {
  232. b.WriteString(fmt.Sprintf("%q", stringVal))
  233. }
  234. }