http urls monitor.

json_formatter.go 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. // DataKey allows users to put all the log entry parameters into a nested dictionary at a given key.
  28. DataKey string
  29. // FieldMap allows users to customize the names of keys for default fields.
  30. // As an example:
  31. // formatter := &JSONFormatter{
  32. // FieldMap: FieldMap{
  33. // FieldKeyTime: "@timestamp",
  34. // FieldKeyLevel: "@level",
  35. // FieldKeyMsg: "@message",
  36. // },
  37. // }
  38. FieldMap FieldMap
  39. }
  40. // Format renders a single log entry
  41. func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
  42. data := make(Fields, len(entry.Data)+3)
  43. for k, v := range entry.Data {
  44. switch v := v.(type) {
  45. case error:
  46. // Otherwise errors are ignored by `encoding/json`
  47. // https://github.com/sirupsen/logrus/issues/137
  48. data[k] = v.Error()
  49. default:
  50. data[k] = v
  51. }
  52. }
  53. if f.DataKey != "" {
  54. newData := make(Fields, 4)
  55. newData[f.DataKey] = data
  56. data = newData
  57. }
  58. prefixFieldClashes(data, f.FieldMap)
  59. timestampFormat := f.TimestampFormat
  60. if timestampFormat == "" {
  61. timestampFormat = defaultTimestampFormat
  62. }
  63. if !f.DisableTimestamp {
  64. data[f.FieldMap.resolve(FieldKeyTime)] = entry.Time.Format(timestampFormat)
  65. }
  66. data[f.FieldMap.resolve(FieldKeyMsg)] = entry.Message
  67. data[f.FieldMap.resolve(FieldKeyLevel)] = entry.Level.String()
  68. serialized, err := json.Marshal(data)
  69. if err != nil {
  70. return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
  71. }
  72. return append(serialized, '\n'), nil
  73. }