From 725aba339f5bc375a2bfa3c2c0dfad2e7ffab4e1 Mon Sep 17 00:00:00 2001 From: alex Date: Sun, 8 Oct 2023 12:54:38 +0200 Subject: [PATCH] added logger --- rslogger/rslogger.go | 82 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 rslogger/rslogger.go diff --git a/rslogger/rslogger.go b/rslogger/rslogger.go new file mode 100644 index 0000000..f29a4a2 --- /dev/null +++ b/rslogger/rslogger.go @@ -0,0 +1,82 @@ +package rslogger + +import ( + "encoding/json" + "fmt" + "os" + "time" + + "github.com/gofiber/fiber/v2" + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" +) + +var usedLogManagerServerUrl string + +func InitLogger(debug bool, colorizedOutput bool, logManagerServerUrl string) { + zerolog.TimeFieldFormat = zerolog.TimeFormatUnix + + if debug { + zerolog.SetGlobalLevel(zerolog.DebugLevel) + } else { + zerolog.SetGlobalLevel(zerolog.InfoLevel) + } + + if colorizedOutput { + log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: "15:04:05"}) + } + + if logManagerServerUrl != "" { + usedLogManagerServerUrl = logManagerServerUrl + } +} + +func getTime() string { + return time.Now().Format("15:04:05 02-01-2006") + " " +} + +func AddSystemLog(format string, v ...any) { + log.Info().Msgf("used log manager server url: %s", usedLogManagerServerUrl) + + go LogManagerRequestClient(fiber.MethodPost, usedLogManagerServerUrl+"/v1/log", LogManagerRequestBody{ + Type: "system", + Logs: []string{"I " + getTime() + fmt.Sprintf(format, v...)}}) +} + +func AddGroupTasksLog(format string, v ...any) { + go LogManagerRequestClient(fiber.MethodPost, usedLogManagerServerUrl+"/v1/log", LogManagerRequestBody{ + Type: "grouptasks", + Logs: []string{"I " + getTime() + fmt.Sprintf(format, v...)}}) +} + +type LogManagerRequestBody struct { + Type string + Logs []string +} + +func LogManagerRequestClient(requestMethod string, url string, body interface{}) { + a := fiber.AcquireAgent() + + req := a.Request() + req.Header.SetMethod(requestMethod) + req.SetRequestURI(url) + req.Header.SetContentType("application/json") + + reqestBodyBytes, err := json.Marshal(body) + + if err != nil { + log.Error().Msgf("Failed to marshal request body, err: %s", err) + return + } + + req.SetBody(reqestBodyBytes) + + if err := a.Parse(); err != nil { + log.Error().Msgf("Failed to parse request, err: %s", err) + return + } + + code, body, _ := a.Bytes() + + log.Info().Msgf("Log manager request, code: %d, body: %s", code, body) +}