formatter.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package logrus
  2. import "time"
  3. const DefaultTimestampFormat = time.RFC3339
  4. // The Formatter interface is used to implement a custom Formatter. It takes an
  5. // `Entry`. It exposes all the fields, including the default ones:
  6. //
  7. // * `entry.Data["msg"]`. The message passed from Info, Warn, Error ..
  8. // * `entry.Data["time"]`. The timestamp.
  9. // * `entry.Data["level"]. The level the entry was logged at.
  10. //
  11. // Any additional fields added with `WithField` or `WithFields` are also in
  12. // `entry.Data`. Format is expected to return an array of bytes which are then
  13. // logged to `logger.Out`.
  14. type Formatter interface {
  15. Format(*Entry) ([]byte, error)
  16. }
  17. // This is to not silently overwrite `time`, `msg` and `level` fields when
  18. // dumping it. If this code wasn't there doing:
  19. //
  20. // logrus.WithField("level", 1).Info("hello")
  21. //
  22. // Would just silently drop the user provided level. Instead with this code
  23. // it'll logged as:
  24. //
  25. // {"level": "info", "fields.level": 1, "msg": "hello", "time": "..."}
  26. //
  27. // It's not exported because it's still using Data in an opinionated way. It's to
  28. // avoid code duplication between the two default formatters.
  29. func prefixFieldClashes(data Fields) {
  30. _, ok := data["time"]
  31. if ok {
  32. data["fields.time"] = data["time"]
  33. }
  34. _, ok = data["msg"]
  35. if ok {
  36. data["fields.msg"] = data["msg"]
  37. }
  38. _, ok = data["level"]
  39. if ok {
  40. data["fields.level"] = data["level"]
  41. }
  42. }