formatter.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package srslog
  2. import (
  3. "fmt"
  4. "os"
  5. "time"
  6. )
  7. const appNameMaxLength = 48 // limit to 48 chars as per RFC5424
  8. // Formatter is a type of function that takes the consituent parts of a
  9. // syslog message and returns a formatted string. A different Formatter is
  10. // defined for each different syslog protocol we support.
  11. type Formatter func(p Priority, hostname, tag, content string) string
  12. // DefaultFormatter is the original format supported by the Go syslog package,
  13. // and is a non-compliant amalgamation of 3164 and 5424 that is intended to
  14. // maximize compatibility.
  15. func DefaultFormatter(p Priority, hostname, tag, content string) string {
  16. timestamp := time.Now().Format(time.RFC3339)
  17. msg := fmt.Sprintf("<%d> %s %s %s[%d]: %s",
  18. p, timestamp, hostname, tag, os.Getpid(), content)
  19. return msg
  20. }
  21. // UnixFormatter omits the hostname, because it is only used locally.
  22. func UnixFormatter(p Priority, hostname, tag, content string) string {
  23. timestamp := time.Now().Format(time.Stamp)
  24. msg := fmt.Sprintf("<%d>%s %s[%d]: %s",
  25. p, timestamp, tag, os.Getpid(), content)
  26. return msg
  27. }
  28. // RFC3164Formatter provides an RFC 3164 compliant message.
  29. func RFC3164Formatter(p Priority, hostname, tag, content string) string {
  30. timestamp := time.Now().Format(time.Stamp)
  31. msg := fmt.Sprintf("<%d>%s %s %s[%d]: %s",
  32. p, timestamp, hostname, tag, os.Getpid(), content)
  33. return msg
  34. }
  35. // if string's length is greater than max, then use the last part
  36. func truncateStartStr(s string, max int) string {
  37. if (len(s) > max) {
  38. return s[len(s) - max:]
  39. }
  40. return s
  41. }
  42. // RFC5424Formatter provides an RFC 5424 compliant message.
  43. func RFC5424Formatter(p Priority, hostname, tag, content string) string {
  44. timestamp := time.Now().Format(time.RFC3339)
  45. pid := os.Getpid()
  46. appName := truncateStartStr(os.Args[0], appNameMaxLength)
  47. msg := fmt.Sprintf("<%d>%d %s %s %s %d %s - %s",
  48. p, 1, timestamp, hostname, appName, pid, tag, content)
  49. return msg
  50. }