json_formatter.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package logrus
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. )
  6. type fieldKey string
  7. type FieldMap map[fieldKey]string
  8. const (
  9. FieldKeyMsg = "msg"
  10. FieldKeyLevel = "level"
  11. FieldKeyTime = "time"
  12. )
  13. func (f FieldMap) resolve(key fieldKey) string {
  14. if k, ok := f[key]; ok {
  15. return k
  16. }
  17. return string(key)
  18. }
  19. type JSONFormatter struct {
  20. // TimestampFormat sets the format used for marshaling timestamps.
  21. TimestampFormat string
  22. // DisableTimestamp allows disabling automatic timestamps in output
  23. DisableTimestamp bool
  24. // FieldMap allows users to customize the names of keys for various fields.
  25. // As an example:
  26. // formatter := &JSONFormatter{
  27. // FieldMap: FieldMap{
  28. // FieldKeyTime: "@timestamp",
  29. // FieldKeyLevel: "@level",
  30. // FieldKeyLevel: "@message",
  31. // },
  32. // }
  33. FieldMap FieldMap
  34. }
  35. func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
  36. data := make(Fields, len(entry.Data)+3)
  37. for k, v := range entry.Data {
  38. switch v := v.(type) {
  39. case error:
  40. // Otherwise errors are ignored by `encoding/json`
  41. // https://github.com/Sirupsen/logrus/issues/137
  42. data[k] = v.Error()
  43. default:
  44. data[k] = v
  45. }
  46. }
  47. prefixFieldClashes(data)
  48. timestampFormat := f.TimestampFormat
  49. if timestampFormat == "" {
  50. timestampFormat = DefaultTimestampFormat
  51. }
  52. if !f.DisableTimestamp {
  53. data[f.FieldMap.resolve(FieldKeyTime)] = entry.Time.Format(timestampFormat)
  54. }
  55. data[f.FieldMap.resolve(FieldKeyMsg)] = entry.Message
  56. data[f.FieldMap.resolve(FieldKeyLevel)] = entry.Level.String()
  57. serialized, err := json.Marshal(data)
  58. if err != nil {
  59. return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
  60. }
  61. return append(serialized, '\n'), nil
  62. }