format.go 6.3 KB

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