Skip to content

Commit

Permalink
Fix loki query log count (#82)
Browse files Browse the repository at this point in the history
* Fix loki query log count
  • Loading branch information
Cairry authored Sep 3, 2024
1 parent 3d125b9 commit f5fecbf
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 9 deletions.
7 changes: 3 additions & 4 deletions alert/eval/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -294,16 +294,13 @@ func loki(ctx *ctx.Context, datasourceId string, rule models.AlertRule) {
return
}

res, err := client.NewLokiClient(datasourceInfo).QueryRange(args)
res, count, err := client.NewLokiClient(datasourceInfo).QueryRange(args)
if err != nil {
global.Logger.Sugar().Errorf("查询 Loki 日志失败 %s", err.Error())
return
}

// count 用于统计日志条数
var count int
for _, v := range res {
count += len(v.Values)
event := func() models.AlertCurEvent {
event := process.BuildEvent(rule)
event.DatasourceId = datasourceId
Expand All @@ -325,6 +322,8 @@ func loki(ctx *ctx.Context, datasourceId string, rule models.AlertRule) {

// 评估告警条件
process.EvalCondition(ctx, event, float64(count), options)
// 只需要评估出第一条日志信息即可
break
}
}

Expand Down
15 changes: 10 additions & 5 deletions pkg/client/loki.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,12 @@ type Result struct {
Values []interface{} `json:"values"`
}

func (lc LokiClient) QueryRange(options QueryOptions) ([]Result, error) {
func (lc LokiClient) QueryRange(options QueryOptions) ([]Result, int, error) {

curTime := time.Now()

if options.Query == "" {
return nil, nil
return nil, 0, nil
}

if options.Direction == "" {
Expand All @@ -73,18 +73,23 @@ func (lc LokiClient) QueryRange(options QueryOptions) ([]Result, error) {
requestURL := lc.BaseURL + args
res, err := http.Get(nil, requestURL)
if err != nil {
return nil, err
return nil, 0, err
}

body, _ := io.ReadAll(res.Body)
var resultData result
err = json.Unmarshal(body, &resultData)
if err != nil {
return nil, err
return nil, 0, err
}

return resultData.Data.Result, nil
// count 用于统计日志条数
var count int
for _, v := range resultData.Data.Result {
count += len(v.Values)
}

return resultData.Data.Result, count, nil
}

func (r Result) GetFingerprint() string {
Expand Down

0 comments on commit f5fecbf

Please sign in to comment.