format.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. package log
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "reflect"
  7. "strconv"
  8. "strings"
  9. "sync"
  10. "sync/atomic"
  11. "time"
  12. )
  13. const (
  14. timeFormat = "2006-01-02T15:04:05-0700"
  15. termTimeFormat = "01-02|15:04:05"
  16. floatFormat = 'f'
  17. termMsgJust = 40
  18. )
  19. // locationTrims are trimmed for display to avoid unwieldy log lines.
  20. var locationTrims = []string{
  21. "github.com/ethereum/go-ethereum/",
  22. "github.com/ethereum/ethash/",
  23. }
  24. // PrintOrigins sets or unsets log location (file:line) printing for terminal
  25. // format output.
  26. func PrintOrigins(print bool) {
  27. if print {
  28. atomic.StoreUint32(&locationEnabled, 1)
  29. } else {
  30. atomic.StoreUint32(&locationEnabled, 0)
  31. }
  32. }
  33. // locationEnabled is an atomic flag controlling whether the terminal formatter
  34. // should append the log locations too when printing entries.
  35. var locationEnabled uint32
  36. // locationLength is the maxmimum path length encountered, which all logs are
  37. // padded to to aid in alignment.
  38. var locationLength uint32
  39. type Format interface {
  40. Format(r *Record) []byte
  41. }
  42. // FormatFunc returns a new Format object which uses
  43. // the given function to perform record formatting.
  44. func FormatFunc(f func(*Record) []byte) Format {
  45. return formatFunc(f)
  46. }
  47. type formatFunc func(*Record) []byte
  48. func (f formatFunc) Format(r *Record) []byte {
  49. return f(r)
  50. }
  51. // TerminalFormat formats log records optimized for human readability on
  52. // a terminal with color-coded level output and terser human friendly timestamp.
  53. // This format should only be used for interactive programs or while developing.
  54. //
  55. // [TIME] [LEVEL] MESAGE key=value key=value ...
  56. //
  57. // Example:
  58. //
  59. // [May 16 20:58:45] [DBUG] remove route ns=haproxy addr=127.0.0.1:50002
  60. //
  61. func TerminalFormat(usecolor bool) Format {
  62. return FormatFunc(func(r *Record) []byte {
  63. var color = 0
  64. if usecolor {
  65. switch r.Lvl {
  66. case LvlCrit:
  67. color = 35
  68. case LvlError:
  69. color = 31
  70. case LvlWarn:
  71. color = 33
  72. case LvlInfo:
  73. color = 32
  74. case LvlDebug:
  75. color = 36
  76. case LvlTrace:
  77. color = 34
  78. }
  79. }
  80. b := &bytes.Buffer{}
  81. lvl := r.Lvl.AlignedString()
  82. if atomic.LoadUint32(&locationEnabled) != 0 {
  83. // Log origin printing was requested, format the location path and line number
  84. location := fmt.Sprintf("%+v", r.Call)
  85. for _, prefix := range locationTrims {
  86. location = strings.TrimPrefix(location, prefix)
  87. }
  88. // Maintain the maximum location length for fancyer alignment
  89. align := int(atomic.LoadUint32(&locationLength))
  90. if align < len(location) {
  91. align = len(location)
  92. atomic.StoreUint32(&locationLength, uint32(align))
  93. }
  94. padding := strings.Repeat(" ", align-len(location))
  95. // Assemble and print the log heading
  96. if color > 0 {
  97. fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s|%s]%s %s ", color, lvl, r.Time.Format(termTimeFormat), location, padding, r.Msg)
  98. } else {
  99. fmt.Fprintf(b, "%s[%s|%s]%s %s ", lvl, r.Time.Format(termTimeFormat), location, padding, r.Msg)
  100. }
  101. } else {
  102. if color > 0 {
  103. fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %s ", color, lvl, r.Time.Format(termTimeFormat), r.Msg)
  104. } else {
  105. fmt.Fprintf(b, "%s[%s] %s ", lvl, r.Time.Format(termTimeFormat), r.Msg)
  106. }
  107. }
  108. // try to justify the log output for short messages
  109. if len(r.Ctx) > 0 && len(r.Msg) < termMsgJust {
  110. b.Write(bytes.Repeat([]byte{' '}, termMsgJust-len(r.Msg)))
  111. }
  112. // print the keys logfmt style
  113. logfmt(b, r.Ctx, color)
  114. return b.Bytes()
  115. })
  116. }
  117. // LogfmtFormat prints records in logfmt format, an easy machine-parseable but human-readable
  118. // format for key/value pairs.
  119. //
  120. // For more details see: http://godoc.org/github.com/kr/logfmt
  121. //
  122. func LogfmtFormat() Format {
  123. return FormatFunc(func(r *Record) []byte {
  124. common := []interface{}{r.KeyNames.Time, r.Time, r.KeyNames.Lvl, r.Lvl, r.KeyNames.Msg, r.Msg}
  125. buf := &bytes.Buffer{}
  126. logfmt(buf, append(common, r.Ctx...), 0)
  127. return buf.Bytes()
  128. })
  129. }
  130. func logfmt(buf *bytes.Buffer, ctx []interface{}, color int) {
  131. for i := 0; i < len(ctx); i += 2 {
  132. if i != 0 {
  133. buf.WriteByte(' ')
  134. }
  135. k, ok := ctx[i].(string)
  136. v := formatLogfmtValue(ctx[i+1])
  137. if !ok {
  138. k, v = errorKey, formatLogfmtValue(k)
  139. }
  140. // XXX: we should probably check that all of your key bytes aren't invalid
  141. if color > 0 {
  142. fmt.Fprintf(buf, "\x1b[%dm%s\x1b[0m=%s", color, k, v)
  143. } else {
  144. buf.WriteString(k)
  145. buf.WriteByte('=')
  146. buf.WriteString(v)
  147. }
  148. }
  149. buf.WriteByte('\n')
  150. }
  151. // JsonFormat formats log records as JSON objects separated by newlines.
  152. // It is the equivalent of JsonFormatEx(false, true).
  153. func JsonFormat() Format {
  154. return JsonFormatEx(false, true)
  155. }
  156. // JsonFormatEx formats log records as JSON objects. If pretty is true,
  157. // records will be pretty-printed. If lineSeparated is true, records
  158. // will be logged with a new line between each record.
  159. func JsonFormatEx(pretty, lineSeparated bool) Format {
  160. jsonMarshal := json.Marshal
  161. if pretty {
  162. jsonMarshal = func(v interface{}) ([]byte, error) {
  163. return json.MarshalIndent(v, "", " ")
  164. }
  165. }
  166. return FormatFunc(func(r *Record) []byte {
  167. props := make(map[string]interface{})
  168. props[r.KeyNames.Time] = r.Time
  169. props[r.KeyNames.Lvl] = r.Lvl.String()
  170. props[r.KeyNames.Msg] = r.Msg
  171. for i := 0; i < len(r.Ctx); i += 2 {
  172. k, ok := r.Ctx[i].(string)
  173. if !ok {
  174. props[errorKey] = fmt.Sprintf("%+v is not a string key", r.Ctx[i])
  175. }
  176. props[k] = formatJsonValue(r.Ctx[i+1])
  177. }
  178. b, err := jsonMarshal(props)
  179. if err != nil {
  180. b, _ = jsonMarshal(map[string]string{
  181. errorKey: err.Error(),
  182. })
  183. return b
  184. }
  185. if lineSeparated {
  186. b = append(b, '\n')
  187. }
  188. return b
  189. })
  190. }
  191. func formatShared(value interface{}) (result interface{}) {
  192. defer func() {
  193. if err := recover(); err != nil {
  194. if v := reflect.ValueOf(value); v.Kind() == reflect.Ptr && v.IsNil() {
  195. result = "nil"
  196. } else {
  197. panic(err)
  198. }
  199. }
  200. }()
  201. switch v := value.(type) {
  202. case time.Time:
  203. return v.Format(timeFormat)
  204. case error:
  205. return v.Error()
  206. case fmt.Stringer:
  207. return v.String()
  208. default:
  209. return v
  210. }
  211. }
  212. func formatJsonValue(value interface{}) interface{} {
  213. value = formatShared(value)
  214. switch value.(type) {
  215. case int, int8, int16, int32, int64, float32, float64, uint, uint8, uint16, uint32, uint64, string:
  216. return value
  217. default:
  218. return fmt.Sprintf("%+v", value)
  219. }
  220. }
  221. // formatValue formats a value for serialization
  222. func formatLogfmtValue(value interface{}) string {
  223. if value == nil {
  224. return "nil"
  225. }
  226. if t, ok := value.(time.Time); ok {
  227. // Performance optimization: No need for escaping since the provided
  228. // timeFormat doesn't have any escape characters, and escaping is
  229. // expensive.
  230. return t.Format(timeFormat)
  231. }
  232. value = formatShared(value)
  233. switch v := value.(type) {
  234. case bool:
  235. return strconv.FormatBool(v)
  236. case float32:
  237. return strconv.FormatFloat(float64(v), floatFormat, 3, 64)
  238. case float64:
  239. return strconv.FormatFloat(v, floatFormat, 3, 64)
  240. case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
  241. return fmt.Sprintf("%d", value)
  242. case string:
  243. return escapeString(v)
  244. default:
  245. return escapeString(fmt.Sprintf("%+v", value))
  246. }
  247. }
  248. var stringBufPool = sync.Pool{
  249. New: func() interface{} { return new(bytes.Buffer) },
  250. }
  251. func escapeString(s string) string {
  252. needsQuotes := false
  253. needsEscape := false
  254. for _, r := range s {
  255. if r <= ' ' || r == '=' || r == '"' {
  256. needsQuotes = true
  257. }
  258. if r == '\\' || r == '"' || r == '\n' || r == '\r' || r == '\t' {
  259. needsEscape = true
  260. }
  261. }
  262. if needsEscape == false && needsQuotes == false {
  263. return s
  264. }
  265. e := stringBufPool.Get().(*bytes.Buffer)
  266. e.WriteByte('"')
  267. for _, r := range s {
  268. switch r {
  269. case '\\', '"':
  270. e.WriteByte('\\')
  271. e.WriteByte(byte(r))
  272. case '\n':
  273. e.WriteString("\\n")
  274. case '\r':
  275. e.WriteString("\\r")
  276. case '\t':
  277. e.WriteString("\\t")
  278. default:
  279. e.WriteRune(r)
  280. }
  281. }
  282. e.WriteByte('"')
  283. var ret string
  284. if needsQuotes {
  285. ret = e.String()
  286. } else {
  287. ret = string(e.Bytes()[1 : e.Len()-1])
  288. }
  289. e.Reset()
  290. stringBufPool.Put(e)
  291. return ret
  292. }