logs-fix-3

This commit is contained in:
Untone 2024-01-22 14:49:58 +03:00
parent 07a26991e9
commit c53ada95eb
3 changed files with 62 additions and 2 deletions

60
server/logs/fmt.go Normal file
View File

@ -0,0 +1,60 @@
package logs
import (
"encoding/json"
"fmt"
"time"
"github.com/sirupsen/logrus"
)
// LogJSONFormatter is a custom log formatter for JSON output
type LogJSONFormatter struct {
}
// Format formats the log entry to JSON
func (f *LogJSONFormatter) Format(entry *logrus.Entry) ([]byte, error) {
data := make(logrus.Fields)
// Include the log level, message, and time in the JSON output
data["level"] = entry.Level.String()
data["msg"] = entry.Message
data["time"] = entry.Time.UTC().Format(time.RFC3339)
// Include additional fields from the entry
for k, v := range entry.Data {
data[k] = v
}
// Marshal the JSON data
jsonData, err := json.Marshal(data)
if err != nil {
return nil, fmt.Errorf("failed to marshal log entry to JSON: %v", err)
}
// Append a newline to the JSON data
return append(jsonData, '\n'), nil
}
// ParseLogLine parses the log line and extracts the log level, message, and time
func ParseLogLine(line string) (logrus.Level, string, time.Time, error) {
var entry struct {
Level string `json:"level"`
Msg string `json:"msg"`
Time time.Time `json:"time"`
}
// Unmarshal the JSON data
err := json.Unmarshal([]byte(line), &entry)
if err != nil {
return logrus.InfoLevel, "", time.Time{}, fmt.Errorf("failed to unmarshal log line: %v", err)
}
// Convert the log level string to logrus.Level
level, err := logrus.ParseLevel(entry.Level)
if err != nil {
return logrus.InfoLevel, "", time.Time{}, fmt.Errorf("failed to parse log level: %v", err)
}
return level, entry.Msg, entry.Time, nil
}

View File

@ -22,7 +22,7 @@ func InitLog(cliLogLevel string) *log.Logger {
// log instance for gin server
log := logrus.New()
log.SetFormatter(LogUTCFormatter{&logrus.TextFormatter{}})
log.SetFormatter(&LogJSONFormatter{})
if cliLogLevel == "" {
cliLogLevel = os.Getenv("LOG_LEVEL")

View File

@ -28,7 +28,7 @@ func main() {
flag.Parse()
// global log level
logrus.SetFormatter(logs.LogUTCFormatter{&logrus.JSONFormatter{}})
logrus.SetFormatter(&logs.LogJSONFormatter{})
constants.VERSION = VERSION