formatter.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package slog
  2. import (
  3. "bytes"
  4. "fmt"
  5. "github.com/sirupsen/logrus"
  6. )
  7. const (
  8. nocolor = 0
  9. red = 31
  10. green = 32
  11. yellow = 33
  12. blue = 34
  13. gray = 39
  14. )
  15. var (
  16. formatParams = map[logrus.Level]formatParam{
  17. logrus.DebugLevel: formatParam{
  18. color: blue,
  19. levelText: "DEBUG",
  20. },
  21. logrus.InfoLevel: formatParam{
  22. color: green,
  23. levelText: "INFO",
  24. },
  25. logrus.WarnLevel: formatParam{
  26. color: yellow,
  27. levelText: "WARN",
  28. },
  29. logrus.ErrorLevel: formatParam{
  30. color: red,
  31. levelText: "ERROR",
  32. },
  33. }
  34. )
  35. type (
  36. formatter struct {
  37. logrus.TextFormatter
  38. }
  39. formatParam struct {
  40. color int
  41. levelText string
  42. }
  43. )
  44. func newFormatter(color bool) *formatter {
  45. return &formatter{
  46. logrus.TextFormatter{
  47. ForceColors: color,
  48. DisableColors: !color,
  49. },
  50. }
  51. }
  52. /**************************
  53. formatter function
  54. **************************/
  55. func (f *formatter) Format(entry *logrus.Entry) ([]byte, error) {
  56. formatParams := formatParams[entry.Level]
  57. b := &bytes.Buffer{}
  58. if f.ForceColors && !f.DisableColors {
  59. fmt.Fprintf(b,
  60. "\x1b[%dm[%-5s]\x1b[0m %s",
  61. formatParams.color,
  62. formatParams.levelText,
  63. entry.Message,
  64. )
  65. } else {
  66. fmt.Fprintf(b,
  67. "[%-5s] %s",
  68. formatParams.levelText,
  69. entry.Message,
  70. )
  71. }
  72. b.WriteByte('\n')
  73. return b.Bytes(), nil
  74. }