json_formatter.go 940 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package logrus
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. )
  6. type JSONFormatter struct {
  7. // TimestampFormat sets the format used for marshaling timestamps.
  8. TimestampFormat string
  9. }
  10. func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
  11. data := make(Fields, len(entry.Data)+3)
  12. for k, v := range entry.Data {
  13. switch v := v.(type) {
  14. case error:
  15. // Otherwise errors are ignored by `encoding/json`
  16. // https://github.com/Sirupsen/logrus/issues/137
  17. data[k] = v.Error()
  18. default:
  19. data[k] = v
  20. }
  21. }
  22. prefixFieldClashes(data)
  23. timestampFormat := f.TimestampFormat
  24. if timestampFormat == "" {
  25. timestampFormat = DefaultTimestampFormat
  26. }
  27. data["time"] = entry.Time.Format(timestampFormat)
  28. data["msg"] = entry.Message
  29. data["level"] = entry.Level.String()
  30. serialized, err := json.Marshal(data)
  31. if err != nil {
  32. return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
  33. }
  34. return append(serialized, '\n'), nil
  35. }