package logger
import (
"encoding/json"
"fmt"
"github.com/coralogix/go-coralogix-sdk"
"github.com/rs/zerolog/pkgerrors"
"os"
"reflect"
"regexp"
"strconv"
"strings"
"time"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
var CoralogixLogger *coralogix.CoralogixLogger
type CoralogixHook struct {
CLogger *coralogix.CoralogixLogger
}
type Event struct {
buf []byte
w zerolog.LevelWriter
level zerolog.Level
done func(msg string)
stack bool // enable error stack trace
ch []zerolog.Hook // hooks from context
skipFrame int
}
func ConvertStruct(source zerolog.Event) Event {
sourceValue := reflect.ValueOf(source)
targetValue := reflect.New(reflect.TypeOf(Event{})).Elem()
for i := 0; i < sourceValue.NumField(); i++ {
field := sourceValue.Type().Field(i)
fieldValue := sourceValue.Field(i)
targetField := targetValue.FieldByName(field.Name)
if targetField.IsValid() && targetField.CanSet() {
targetField.Set(fieldValue)
}
}
return targetValue.Interface().(Event)
}
func (t *CoralogixHook) Run(
e *zerolog.Event,
level zerolog.Level,
message string,
) {
abc := *e
fmt.Println("srs")
fmt.Println(abc)
//e.Func(func(e *zerolog.Event) {})
fmt.Println("srs ends")
re := regexp.MustCompile(`\{\[([^]]+)\]`)
match := re.FindStringSubmatch(fmt.Sprint(abc))
if len(match) > 1 {
firstElement := match[1]
fmt.Println(firstElement)
} else {
fmt.Println("No match found.")
}
var sv []byte
numbers := strings.Split(match[1], " ")
for _, numberStr := range numbers {
number, err := strconv.Atoi(numberStr)
if err != nil {
fmt.Printf("Error converting '%s' to integer: %s\n", numberStr, err.Error())
continue
}
// Process the integer
sv = append(sv, byte(number))
}
fmt.Println("srs1")
fmt.Println(string(sv))
fmt.Println("srs1 end")
data := map[string]interface{}{
"logType": level.String(),
"level": level,
"message": message,
}
jsonBytes, err := json.Marshal(data)
if err != nil {
fmt.Println("Error:", err)
return
}
jsonMsg := string(jsonBytes)
if int(level) >= 2 {
if level == 0 {
t.CLogger.Debug(jsonMsg)
} else if level == 1 {
t.CLogger.Info(jsonMsg)
} else if level == 2 {
t.CLogger.Warning(jsonMsg)
} else if level == 3 {
t.CLogger.Error(jsonMsg)
}
}
}
// Setup is used to setup the logger in the desired format
func Setup() {
zerolog.SetGlobalLevel(zerolog.DebugLevel)
zerolog.TimeFieldFormat = time.RFC3339Nano
zerolog.ErrorStackMarshaler = pkgerrors.MarshalStack
log.Logger = zerolog.New(os.Stdout).With().Timestamp().Logger().Output(zerolog.ConsoleWriter{
Out: os.Stdout,
NoColor: true,
TimeFormat: "15:04:05.000",
})
log.Info().Msgf("Logger setup completed")
}
func CoralogixSetup() CoralogixHook {
CoralogixLogger = coralogix.NewCoralogixLogger(
"88c4909f-3fcd-7683-712e-083556c750ff",
"prs-test",
"prs-test")
hook := CoralogixHook{
CLogger: CoralogixLogger,
}
log.Logger = log.Logger.Hook(&hook)
return hook
}