format.go 6.2 KB

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