format.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package log
  2. import (
  3. "context"
  4. "strconv"
  5. "strings"
  6. "time"
  7. F "github.com/sagernet/sing/common/format"
  8. "github.com/logrusorgru/aurora"
  9. )
  10. type Formatter struct {
  11. BaseTime time.Time
  12. DisableColors bool
  13. DisableTimestamp bool
  14. FullTimestamp bool
  15. TimestampFormat string
  16. }
  17. func (f Formatter) Format(ctx context.Context, level Level, tag string, message string, timestamp time.Time) string {
  18. levelString := strings.ToUpper(FormatLevel(level))
  19. if !f.DisableColors {
  20. switch level {
  21. case LevelDebug, LevelTrace:
  22. levelString = aurora.White(levelString).String()
  23. case LevelInfo:
  24. levelString = aurora.Cyan(levelString).String()
  25. case LevelWarn:
  26. levelString = aurora.Yellow(levelString).String()
  27. case LevelError, LevelFatal, LevelPanic:
  28. levelString = aurora.Red(levelString).String()
  29. }
  30. }
  31. if tag != "" {
  32. message = tag + ": " + message
  33. }
  34. var id uint32
  35. var hasId bool
  36. if ctx != nil {
  37. id, hasId = IDFromContext(ctx)
  38. }
  39. if hasId {
  40. if !f.DisableColors {
  41. var color aurora.Color
  42. color = aurora.Color(uint8(id))
  43. color %= 215
  44. row := uint(color / 36)
  45. column := uint(color % 36)
  46. var r, g, b float32
  47. r = float32(row * 51)
  48. g = float32(column / 6 * 51)
  49. b = float32((column % 6) * 51)
  50. luma := 0.2126*r + 0.7152*g + 0.0722*b
  51. if luma < 60 {
  52. row = 5 - row
  53. column = 35 - column
  54. color = aurora.Color(row*36 + column)
  55. }
  56. color += 16
  57. color = color << 16
  58. color |= 1 << 14
  59. message = F.ToString("[", aurora.Colorize(id, color).String(), "] ", message)
  60. } else {
  61. message = F.ToString("[", id, "] ", message)
  62. }
  63. }
  64. switch {
  65. case f.DisableTimestamp:
  66. message = levelString + " " + message
  67. case f.FullTimestamp:
  68. message = F.ToString(int(timestamp.Sub(f.BaseTime)/time.Second)) + " " + levelString + " " + message
  69. default:
  70. message = levelString + "[" + xd(int(timestamp.Sub(f.BaseTime)/time.Second), 4) + "] " + message
  71. }
  72. return message
  73. }
  74. func xd(value int, x int) string {
  75. message := strconv.Itoa(value)
  76. for len(message) < x {
  77. message = "0" + message
  78. }
  79. return message
  80. }