You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
1.8 KiB

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