format.go 5.6 KB

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