log_writer.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. crashRegex := regexp.MustCompile(`(?i)(panic|exception|stack trace|fatal error)`)
  15. // Convert the data to a string
  16. message := strings.TrimSpace(string(m))
  17. // Check if the message contains a crash
  18. if crashRegex.MatchString(message) {
  19. logger.Debug("Core crash detected:\n", message)
  20. lw.lastLine = message
  21. err1 := writeCrachReport(m)
  22. if err1 != nil {
  23. logger.Error("Unable to write crash report:", err1)
  24. }
  25. return len(m), nil
  26. }
  27. regex := regexp.MustCompile(`^(\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2}) \[([^\]]+)\] (.+)$`)
  28. messages := strings.Split(message, "\n")
  29. for _, msg := range messages {
  30. matches := regex.FindStringSubmatch(msg)
  31. if len(matches) > 3 {
  32. level := matches[2]
  33. msgBody := matches[3]
  34. // Map the level to the appropriate logger function
  35. switch level {
  36. case "Debug":
  37. logger.Debug("XRAY: " + msgBody)
  38. case "Info":
  39. logger.Info("XRAY: " + msgBody)
  40. case "Warning":
  41. logger.Warning("XRAY: " + msgBody)
  42. case "Error":
  43. logger.Error("XRAY: " + msgBody)
  44. default:
  45. logger.Debug("XRAY: " + msg)
  46. }
  47. lw.lastLine = ""
  48. } else if msg != "" {
  49. logger.Debug("XRAY: " + msg)
  50. lw.lastLine = msg
  51. }
  52. }
  53. return len(m), nil
  54. }