format.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. package log
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "math/big"
  7. "reflect"
  8. "strconv"
  9. "strings"
  10. "sync"
  11. "sync/atomic"
  12. "time"
  13. "unicode/utf8"
  14. )
  15. const (
  16. timeFormat = "2006-01-02T15:04:05-0700"
  17. termTimeFormat = "01-02|15:04:05.000"
  18. floatFormat = 'f'
  19. termMsgJust = 40
  20. termCtxMaxPadding = 40
  21. )
  22. // locationTrims are trimmed for display to avoid unwieldy log lines.
  23. var locationTrims = []string{
  24. "github.com/ethereum/go-ethereum/",
  25. }
  26. // PrintOrigins sets or unsets log location (file:line) printing for terminal
  27. // format output.
  28. func PrintOrigins(print bool) {
  29. if print {
  30. atomic.StoreUint32(&locationEnabled, 1)
  31. } else {
  32. atomic.StoreUint32(&locationEnabled, 0)
  33. }
  34. }
  35. // locationEnabled is an atomic flag controlling whether the terminal formatter
  36. // should append the log locations too when printing entries.
  37. var locationEnabled uint32
  38. // locationLength is the maxmimum path length encountered, which all logs are
  39. // padded to to aid in alignment.
  40. var locationLength uint32
  41. // fieldPadding is a global map with maximum field value lengths seen until now
  42. // to allow padding log contexts in a bit smarter way.
  43. var fieldPadding = make(map[string]int)
  44. // fieldPaddingLock is a global mutex protecting the field padding map.
  45. var fieldPaddingLock sync.RWMutex
  46. type Format interface {
  47. Format(r *Record) []byte
  48. }
  49. // FormatFunc returns a new Format object which uses
  50. // the given function to perform record formatting.
  51. func FormatFunc(f func(*Record) []byte) Format {
  52. return formatFunc(f)
  53. }
  54. type formatFunc func(*Record) []byte
  55. func (f formatFunc) Format(r *Record) []byte {
  56. return f(r)
  57. }
  58. // TerminalStringer is an analogous interface to the stdlib stringer, allowing
  59. // own types to have custom shortened serialization formats when printed to the
  60. // screen.
  61. type TerminalStringer interface {
  62. TerminalString() string
  63. }
  64. // TerminalFormat formats log records optimized for human readability on
  65. // a terminal with color-coded level output and terser human friendly timestamp.
  66. // This format should only be used for interactive programs or while developing.
  67. //
  68. // [LEVEL] [TIME] MESSAGE key=value key=value ...
  69. //
  70. // Example:
  71. //
  72. // [DBUG] [May 16 20:58:45] remove route ns=haproxy addr=127.0.0.1:50002
  73. //
  74. func TerminalFormat(usecolor bool) Format {
  75. return FormatFunc(func(r *Record) []byte {
  76. var color = 0
  77. if usecolor {
  78. switch r.Lvl {
  79. case LvlCrit:
  80. color = 35
  81. case LvlError:
  82. color = 31
  83. case LvlWarn:
  84. color = 33
  85. case LvlInfo:
  86. color = 32
  87. case LvlDebug:
  88. color = 36
  89. case LvlTrace:
  90. color = 34
  91. }
  92. }
  93. b := &bytes.Buffer{}
  94. lvl := r.Lvl.AlignedString()
  95. if atomic.LoadUint32(&locationEnabled) != 0 {
  96. // Log origin printing was requested, format the location path and line number
  97. location := fmt.Sprintf("%+v", r.Call)
  98. for _, prefix := range locationTrims {
  99. location = strings.TrimPrefix(location, prefix)
  100. }
  101. // Maintain the maximum location length for fancyer alignment
  102. align := int(atomic.LoadUint32(&locationLength))
  103. if align < len(location) {
  104. align = len(location)
  105. atomic.StoreUint32(&locationLength, uint32(align))
  106. }
  107. padding := strings.Repeat(" ", align-len(location))
  108. // Assemble and print the log heading
  109. if color > 0 {
  110. fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s|%s]%s %s ", color, lvl, r.Time.Format(termTimeFormat), location, padding, r.Msg)
  111. } else {
  112. fmt.Fprintf(b, "%s[%s|%s]%s %s ", lvl, r.Time.Format(termTimeFormat), location, padding, r.Msg)
  113. }
  114. } else {
  115. if color > 0 {
  116. fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %s ", color, lvl, r.Time.Format(termTimeFormat), r.Msg)
  117. } else {
  118. fmt.Fprintf(b, "%s[%s] %s ", lvl, r.Time.Format(termTimeFormat), r.Msg)
  119. }
  120. }
  121. // try to justify the log output for short messages
  122. length := utf8.RuneCountInString(r.Msg)
  123. if len(r.Ctx) > 0 && length < termMsgJust {
  124. b.Write(bytes.Repeat([]byte{' '}, termMsgJust-length))
  125. }
  126. // print the keys logfmt style
  127. logfmt(b, r.Ctx, color, true)
  128. return b.Bytes()
  129. })
  130. }
  131. // LogfmtFormat prints records in logfmt format, an easy machine-parseable but human-readable
  132. // format for key/value pairs.
  133. //
  134. // For more details see: http://godoc.org/github.com/kr/logfmt
  135. //
  136. func LogfmtFormat() Format {
  137. return FormatFunc(func(r *Record) []byte {
  138. common := []interface{}{r.KeyNames.Time, r.Time, r.KeyNames.Lvl, r.Lvl, r.KeyNames.Msg, r.Msg}
  139. buf := &bytes.Buffer{}
  140. logfmt(buf, append(common, r.Ctx...), 0, false)
  141. return buf.Bytes()
  142. })
  143. }
  144. func logfmt(buf *bytes.Buffer, ctx []interface{}, color int, term bool) {
  145. for i := 0; i < len(ctx); i += 2 {
  146. if i != 0 {
  147. buf.WriteByte(' ')
  148. }
  149. k, ok := ctx[i].(string)
  150. v := formatLogfmtValue(ctx[i+1], term)
  151. if !ok {
  152. k, v = errorKey, formatLogfmtValue(k, term)
  153. }
  154. // XXX: we should probably check that all of your key bytes aren't invalid
  155. fieldPaddingLock.RLock()
  156. padding := fieldPadding[k]
  157. fieldPaddingLock.RUnlock()
  158. length := utf8.RuneCountInString(v)
  159. if padding < length && length <= termCtxMaxPadding {
  160. padding = length
  161. fieldPaddingLock.Lock()
  162. fieldPadding[k] = padding
  163. fieldPaddingLock.Unlock()
  164. }
  165. if color > 0 {
  166. fmt.Fprintf(buf, "\x1b[%dm%s\x1b[0m=", color, k)
  167. } else {
  168. buf.WriteString(k)
  169. buf.WriteByte('=')
  170. }
  171. buf.WriteString(v)
  172. if i < len(ctx)-2 && padding > length {
  173. buf.Write(bytes.Repeat([]byte{' '}, padding-length))
  174. }
  175. }
  176. buf.WriteByte('\n')
  177. }
  178. // JSONFormat formats log records as JSON objects separated by newlines.
  179. // It is the equivalent of JSONFormatEx(false, true).
  180. func JSONFormat() Format {
  181. return JSONFormatEx(false, true)
  182. }
  183. // JSONFormatOrderedEx formats log records as JSON arrays. If pretty is true,
  184. // records will be pretty-printed. If lineSeparated is true, records
  185. // will be logged with a new line between each record.
  186. func JSONFormatOrderedEx(pretty, lineSeparated bool) Format {
  187. jsonMarshal := json.Marshal
  188. if pretty {
  189. jsonMarshal = func(v interface{}) ([]byte, error) {
  190. return json.MarshalIndent(v, "", " ")
  191. }
  192. }
  193. return FormatFunc(func(r *Record) []byte {
  194. props := make(map[string]interface{})
  195. props[r.KeyNames.Time] = r.Time
  196. props[r.KeyNames.Lvl] = r.Lvl.String()
  197. props[r.KeyNames.Msg] = r.Msg
  198. ctx := make([]string, len(r.Ctx))
  199. for i := 0; i < len(r.Ctx); i += 2 {
  200. k, ok := r.Ctx[i].(string)
  201. if !ok {
  202. props[errorKey] = fmt.Sprintf("%+v is not a string key,", r.Ctx[i])
  203. }
  204. ctx[i] = k
  205. ctx[i+1] = formatLogfmtValue(r.Ctx[i+1], true)
  206. }
  207. props[r.KeyNames.Ctx] = ctx
  208. b, err := jsonMarshal(props)
  209. if err != nil {
  210. b, _ = jsonMarshal(map[string]string{
  211. errorKey: err.Error(),
  212. })
  213. return b
  214. }
  215. if lineSeparated {
  216. b = append(b, '\n')
  217. }
  218. return b
  219. })
  220. }
  221. // JSONFormatEx formats log records as JSON objects. If pretty is true,
  222. // records will be pretty-printed. If lineSeparated is true, records
  223. // will be logged with a new line between each record.
  224. func JSONFormatEx(pretty, lineSeparated bool) Format {
  225. jsonMarshal := json.Marshal
  226. if pretty {
  227. jsonMarshal = func(v interface{}) ([]byte, error) {
  228. return json.MarshalIndent(v, "", " ")
  229. }
  230. }
  231. return FormatFunc(func(r *Record) []byte {
  232. props := make(map[string]interface{})
  233. props[r.KeyNames.Time] = r.Time
  234. props[r.KeyNames.Lvl] = r.Lvl.String()
  235. props[r.KeyNames.Msg] = r.Msg
  236. for i := 0; i < len(r.Ctx); i += 2 {
  237. k, ok := r.Ctx[i].(string)
  238. if !ok {
  239. props[errorKey] = fmt.Sprintf("%+v is not a string key", r.Ctx[i])
  240. }
  241. props[k] = formatJSONValue(r.Ctx[i+1])
  242. }
  243. b, err := jsonMarshal(props)
  244. if err != nil {
  245. b, _ = jsonMarshal(map[string]string{
  246. errorKey: err.Error(),
  247. })
  248. return b
  249. }
  250. if lineSeparated {
  251. b = append(b, '\n')
  252. }
  253. return b
  254. })
  255. }
  256. func formatShared(value interface{}) (result interface{}) {
  257. defer func() {
  258. if err := recover(); err != nil {
  259. if v := reflect.ValueOf(value); v.Kind() == reflect.Ptr && v.IsNil() {
  260. result = "nil"
  261. } else {
  262. panic(err)
  263. }
  264. }
  265. }()
  266. switch v := value.(type) {
  267. case time.Time:
  268. return v.Format(timeFormat)
  269. case error:
  270. return v.Error()
  271. case fmt.Stringer:
  272. return v.String()
  273. default:
  274. return v
  275. }
  276. }
  277. func formatJSONValue(value interface{}) interface{} {
  278. value = formatShared(value)
  279. switch value.(type) {
  280. case int, int8, int16, int32, int64, float32, float64, uint, uint8, uint16, uint32, uint64, string:
  281. return value
  282. default:
  283. return fmt.Sprintf("%+v", value)
  284. }
  285. }
  286. // formatValue formats a value for serialization
  287. func formatLogfmtValue(value interface{}, term bool) string {
  288. if value == nil {
  289. return "nil"
  290. }
  291. switch v := value.(type) {
  292. case time.Time:
  293. // Performance optimization: No need for escaping since the provided
  294. // timeFormat doesn't have any escape characters, and escaping is
  295. // expensive.
  296. return v.Format(timeFormat)
  297. case *big.Int:
  298. // Big ints get consumed by the Stringer clause so we need to handle
  299. // them earlier on.
  300. if v == nil {
  301. return "<nil>"
  302. }
  303. return formatLogfmtBigInt(v)
  304. }
  305. if term {
  306. if s, ok := value.(TerminalStringer); ok {
  307. // Custom terminal stringer provided, use that
  308. return escapeString(s.TerminalString())
  309. }
  310. }
  311. value = formatShared(value)
  312. switch v := value.(type) {
  313. case bool:
  314. return strconv.FormatBool(v)
  315. case float32:
  316. return strconv.FormatFloat(float64(v), floatFormat, 3, 64)
  317. case float64:
  318. return strconv.FormatFloat(v, floatFormat, 3, 64)
  319. case int8, uint8:
  320. return fmt.Sprintf("%d", value)
  321. case int:
  322. return FormatLogfmtInt64(int64(v))
  323. case int16:
  324. return FormatLogfmtInt64(int64(v))
  325. case int32:
  326. return FormatLogfmtInt64(int64(v))
  327. case int64:
  328. return FormatLogfmtInt64(v)
  329. case uint:
  330. return FormatLogfmtUint64(uint64(v))
  331. case uint16:
  332. return FormatLogfmtUint64(uint64(v))
  333. case uint32:
  334. return FormatLogfmtUint64(uint64(v))
  335. case uint64:
  336. return FormatLogfmtUint64(v)
  337. case string:
  338. return escapeString(v)
  339. default:
  340. return escapeString(fmt.Sprintf("%+v", value))
  341. }
  342. }
  343. // FormatLogfmtInt64 formats a potentially big number in a friendlier split format.
  344. func FormatLogfmtInt64(n int64) string {
  345. if n < 0 {
  346. return formatLogfmtUint64(uint64(-n), true)
  347. }
  348. return formatLogfmtUint64(uint64(n), false)
  349. }
  350. // FormatLogfmtUint64 formats a potentially big number in a friendlier split format.
  351. func FormatLogfmtUint64(n uint64) string {
  352. return formatLogfmtUint64(n, false)
  353. }
  354. func formatLogfmtUint64(n uint64, neg bool) string {
  355. // Small numbers are fine as is
  356. if n < 100000 {
  357. if neg {
  358. return strconv.Itoa(-int(n))
  359. } else {
  360. return strconv.Itoa(int(n))
  361. }
  362. }
  363. // Large numbers should be split
  364. const maxLength = 26
  365. var (
  366. out = make([]byte, maxLength)
  367. i = maxLength - 1
  368. comma = 0
  369. )
  370. for ; n > 0; i-- {
  371. if comma == 3 {
  372. comma = 0
  373. out[i] = ','
  374. } else {
  375. comma++
  376. out[i] = '0' + byte(n%10)
  377. n /= 10
  378. }
  379. }
  380. if neg {
  381. out[i] = '-'
  382. i--
  383. }
  384. return string(out[i+1:])
  385. }
  386. var big1000 = big.NewInt(1000)
  387. // formatLogfmtBigInt formats a potentially gigantic number in a friendlier split
  388. // format.
  389. func formatLogfmtBigInt(n *big.Int) string {
  390. // Most number don't need fancy handling, just downcast
  391. if n.IsUint64() {
  392. return FormatLogfmtUint64(n.Uint64())
  393. }
  394. if n.IsInt64() {
  395. return FormatLogfmtInt64(n.Int64())
  396. }
  397. // Ok, huge number needs huge effort
  398. groups := make([]string, 0, 8) // random initial size to cover most cases
  399. for n.Cmp(big1000) >= 0 {
  400. _, mod := n.DivMod(n, big1000, nil)
  401. groups = append(groups, fmt.Sprintf("%03d", mod))
  402. }
  403. groups = append(groups, n.String())
  404. last := len(groups) - 1
  405. for i := 0; i < len(groups)/2; i++ {
  406. groups[i], groups[last-i] = groups[last-i], groups[i]
  407. }
  408. return strings.Join(groups, ",")
  409. }
  410. // escapeString checks if the provided string needs escaping/quoting, and
  411. // calls strconv.Quote if needed
  412. func escapeString(s string) string {
  413. needsQuoting := false
  414. for _, r := range s {
  415. // We quote everything below " (0x34) and above~ (0x7E), plus equal-sign
  416. if r <= '"' || r > '~' || r == '=' {
  417. needsQuoting = true
  418. break
  419. }
  420. }
  421. if !needsQuoting {
  422. return s
  423. }
  424. return strconv.Quote(s)
  425. }