2023-12-10 12:07:50 +00:00
|
|
|
package xray
|
|
|
|
|
|
|
|
import (
|
|
|
|
"strings"
|
|
|
|
"x-ui/logger"
|
|
|
|
)
|
|
|
|
|
|
|
|
func NewLogWriter() *LogWriter {
|
2024-02-10 01:51:16 +00:00
|
|
|
return &LogWriter{
|
|
|
|
listeners: &[]func(line string){},
|
|
|
|
}
|
2023-12-10 12:07:50 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type LogWriter struct {
|
2024-02-10 01:51:16 +00:00
|
|
|
lastLine string
|
|
|
|
listeners *[]func(line string)
|
2023-12-10 12:07:50 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (lw *LogWriter) Write(m []byte) (n int, err error) {
|
|
|
|
// Convert the data to a string
|
|
|
|
message := strings.TrimSpace(string(m))
|
|
|
|
messages := strings.Split(message, "\n")
|
|
|
|
lw.lastLine = messages[len(messages)-1]
|
|
|
|
|
|
|
|
for _, msg := range messages {
|
2024-01-10 12:46:18 +00:00
|
|
|
messageBody := msg
|
|
|
|
|
2023-12-10 12:07:50 +00:00
|
|
|
// Remove timestamp
|
2024-01-10 12:46:18 +00:00
|
|
|
splittedMsg := strings.SplitN(msg, " ", 3)
|
|
|
|
if len(splittedMsg) > 2 {
|
|
|
|
messageBody = strings.TrimSpace(strings.SplitN(msg, " ", 3)[2])
|
|
|
|
}
|
2023-12-10 12:07:50 +00:00
|
|
|
|
|
|
|
// Find level in []
|
|
|
|
startIndex := strings.Index(messageBody, "[")
|
|
|
|
endIndex := strings.Index(messageBody, "]")
|
2024-02-03 11:54:39 +00:00
|
|
|
if startIndex != -1 && endIndex != -1 && startIndex < endIndex {
|
2023-12-10 12:07:50 +00:00
|
|
|
level := strings.TrimSpace(messageBody[startIndex+1 : endIndex])
|
2024-02-10 01:51:16 +00:00
|
|
|
rawMsg := strings.TrimSpace(messageBody[endIndex+1:])
|
|
|
|
msgBody := "XRAY: " + rawMsg
|
2023-12-10 12:07:50 +00:00
|
|
|
|
|
|
|
// Map the level to the appropriate logger function
|
|
|
|
switch level {
|
|
|
|
case "Debug":
|
|
|
|
logger.Debug(msgBody)
|
|
|
|
case "Info":
|
|
|
|
logger.Info(msgBody)
|
|
|
|
case "Warning":
|
|
|
|
logger.Warning(msgBody)
|
|
|
|
case "Error":
|
|
|
|
logger.Error(msgBody)
|
|
|
|
default:
|
|
|
|
logger.Debug("XRAY: " + msg)
|
|
|
|
}
|
2024-02-10 01:51:16 +00:00
|
|
|
|
|
|
|
// Notify listeners of the message
|
|
|
|
for _, listener := range *lw.listeners {
|
|
|
|
listener(messageBody)
|
|
|
|
}
|
2023-12-10 12:07:50 +00:00
|
|
|
} else if msg != "" {
|
|
|
|
logger.Debug("XRAY: " + msg)
|
|
|
|
return len(m), nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return len(m), nil
|
|
|
|
}
|
2024-02-10 01:51:16 +00:00
|
|
|
|
|
|
|
// SetListener adds a listener to the log writer
|
|
|
|
// The listener will be called with each line of the log
|
|
|
|
// that is written to the log writer
|
|
|
|
// We use this method to prevent reading the log file for better performance
|
|
|
|
func (lw *LogWriter) SetListener(listener func(line string)) {
|
|
|
|
*lw.listeners = append(*lw.listeners, listener)
|
|
|
|
}
|