clf.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package logging
  2. import (
  3. "bytes"
  4. "fmt"
  5. "strconv"
  6. "time"
  7. "github.com/sirupsen/logrus"
  8. )
  9. var clfFields = [...]string{
  10. "request-id", "remote-address", "name", "user-id", "time", "duration", "method", "path", "protocol", "status", "size",
  11. }
  12. // CommonLogFormat implements the logrus.Formatter interface it writes logrus
  13. // entries using a CLF format prepended by the request-id.
  14. type CommonLogFormat struct{}
  15. // Format implements the logrus.Formatter interface. It returns the given
  16. // logrus entry as a CLF line with the following format:
  17. //
  18. // <request-id> <remote-address> <name> <user-id> <time> <duration> "<method> <path> <protocol>" <status> <size>
  19. //
  20. // If a field is not known, the hyphen symbol (-) will be used.
  21. func (f *CommonLogFormat) Format(entry *logrus.Entry) ([]byte, error) {
  22. data := make([]string, len(clfFields))
  23. for i, name := range clfFields {
  24. if v, ok := entry.Data[name]; ok {
  25. switch v := v.(type) {
  26. case error:
  27. data[i] = v.Error() //nolint:gosec // i is bounded by len(clfFields)
  28. case string:
  29. if v == "" {
  30. data[i] = "-" //nolint:gosec // i is bounded by len(clfFields)
  31. } else {
  32. data[i] = v //nolint:gosec // i is bounded by len(clfFields)
  33. }
  34. case time.Time:
  35. data[i] = v.Format(time.RFC3339) //nolint:gosec // i is bounded by len(clfFields)
  36. case time.Duration:
  37. data[i] = strconv.FormatInt(int64(v/time.Millisecond), 10) //nolint:gosec // i is bounded by len(clfFields)
  38. case int:
  39. data[i] = strconv.FormatInt(int64(v), 10) //nolint:gosec // i is bounded by len(clfFields)
  40. case int64:
  41. data[i] = strconv.FormatInt(v, 10) //nolint:gosec // i is bounded by len(clfFields)
  42. default:
  43. data[i] = fmt.Sprintf("%v", v) //nolint:gosec // i is bounded by len(clfFields)
  44. }
  45. } else {
  46. data[i] = "-" //nolint:gosec // i is bounded by len(clfFields)
  47. }
  48. }
  49. var buf bytes.Buffer
  50. buf.WriteString(data[0])
  51. buf.WriteByte(' ')
  52. buf.WriteString(data[1])
  53. buf.WriteByte(' ')
  54. buf.WriteString(data[2])
  55. buf.WriteByte(' ')
  56. buf.WriteString(data[3])
  57. buf.WriteByte(' ')
  58. buf.WriteString(data[4])
  59. buf.WriteByte(' ')
  60. buf.WriteString(data[5])
  61. buf.WriteString(" \"")
  62. buf.WriteString(data[6])
  63. buf.WriteByte(' ')
  64. buf.WriteString(data[7])
  65. buf.WriteByte(' ')
  66. buf.WriteString(data[8])
  67. buf.WriteString("\" ")
  68. buf.WriteString(data[9])
  69. buf.WriteByte(' ')
  70. buf.WriteString(data[10])
  71. buf.WriteByte('\n')
  72. return buf.Bytes(), nil
  73. }