log_writer.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package xray
  2. import (
  3. "regexp"
  4. "strings"
  5. "x-ui/logger"
  6. )
  7. func NewLogWriter() *LogWriter {
  8. return &LogWriter{}
  9. }
  10. type LogWriter struct {
  11. lastLine string
  12. }
  13. func (lw *LogWriter) Write(m []byte) (n int, err error) {
  14. regex := regexp.MustCompile(`^(\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2}) \[([^\]]+)\] (.+)$`)
  15. // Convert the data to a string
  16. message := strings.TrimSpace(string(m))
  17. messages := strings.Split(message, "\n")
  18. lw.lastLine = messages[len(messages)-1]
  19. for _, msg := range messages {
  20. matches := regex.FindStringSubmatch(msg)
  21. if len(matches) > 3 {
  22. level := matches[2]
  23. msgBody := matches[3]
  24. // Map the level to the appropriate logger function
  25. switch level {
  26. case "Debug":
  27. logger.Debug("XRAY: " + msgBody)
  28. case "Info":
  29. logger.Info("XRAY: " + msgBody)
  30. case "Warning":
  31. logger.Warning("XRAY: " + msgBody)
  32. case "Error":
  33. logger.Error("XRAY: " + msgBody)
  34. default:
  35. logger.Debug("XRAY: " + msg)
  36. }
  37. } else if msg != "" {
  38. logger.Debug("XRAY: " + msg)
  39. return len(m), nil
  40. }
  41. }
  42. return len(m), nil
  43. }