2023-11-23 07:39:52 +00:00
|
|
|
package logger
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"context"
|
|
|
|
"encoding/json"
|
2023-11-27 08:45:12 +00:00
|
|
|
"errors"
|
2023-11-23 07:39:52 +00:00
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
cfgSignoz SignozConfiguration
|
|
|
|
)
|
|
|
|
|
|
|
|
// InitSignoz ...
|
|
|
|
func InitSignoz(config SignozConfiguration) {
|
|
|
|
cfgSignoz = config
|
|
|
|
}
|
|
|
|
|
|
|
|
// SendLogToSignoz ...
|
|
|
|
func SendLogToSignoz(ctx context.Context, payload SignozLogPayload) error {
|
2023-11-27 08:45:12 +00:00
|
|
|
if cfgSignoz.Logs.EndPoint == "" {
|
|
|
|
return errors.New("end point not found")
|
|
|
|
}
|
2023-11-23 07:39:52 +00:00
|
|
|
client := http.Client{}
|
|
|
|
b := generateBody(ctx, payload)
|
2023-11-27 08:45:12 +00:00
|
|
|
r, errRequest := http.NewRequest(http.MethodPost, cfgSignoz.Logs.EndPoint, bytes.NewBuffer(b))
|
2023-11-23 07:39:52 +00:00
|
|
|
if errRequest != nil {
|
|
|
|
return errRequest
|
|
|
|
}
|
|
|
|
r.Header.Set("Content-Type", "application/json")
|
|
|
|
resp, errRequest := client.Do(r)
|
|
|
|
if errRequest != nil {
|
|
|
|
return errRequest
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func generateBody(ctx context.Context, info SignozLogPayload) []byte {
|
|
|
|
var (
|
|
|
|
timestamp = time.Now().Unix()
|
|
|
|
payload = logData{
|
|
|
|
SeverityNumber: info.SeverityLevel,
|
|
|
|
SeverityText: getSeverityLevelText(info.SeverityLevel),
|
|
|
|
Timestamp: timestamp,
|
|
|
|
Source: cfgSignoz.ServiceName,
|
|
|
|
Message: "",
|
|
|
|
}
|
|
|
|
)
|
|
|
|
body := map[string]interface{}{
|
|
|
|
"message": info.Message,
|
|
|
|
"level_number": info.SeverityLevel,
|
|
|
|
"level": getSeverityLevelText(info.SeverityLevel),
|
|
|
|
"request_id": "",
|
|
|
|
"data": info.Data,
|
|
|
|
}
|
|
|
|
rid := ctx.Value(CtxKeyRequestID)
|
|
|
|
if rid != nil {
|
|
|
|
body["request_id"] = rid.(string)
|
|
|
|
payload.TraceID = rid.(string)
|
|
|
|
payload.SpanID = rid.(string)
|
|
|
|
}
|
|
|
|
msg, _ := json.Marshal(body)
|
|
|
|
payload.Message = string(msg)
|
|
|
|
b, _ := json.Marshal(payload)
|
|
|
|
return b
|
|
|
|
}
|
|
|
|
|
|
|
|
func getSeverityLevelText(level int) string {
|
|
|
|
return MapStringSeverityLevel[level]
|
|
|
|
}
|