4

I'm trying to customize an Email template from AlertManager that uses a Go html template that prints a list of alerts using the following construct :

{{ range .Alerts.Firing }}

It gets inserted into the template like this :

func (n *Email) Notify(ctx context.Context, as ...*types.Alert) (bool, error) {
   ...
   data = n.tmpl.Data(receiverName(ctx), groupLabels(ctx), as...)
   ...
}

Alert being defined like this :

type Alert struct {
    Labels LabelSet `json:"labels"`

    Annotations LabelSet `json:"annotations"`

    StartsAt     time.Time `json:"startsAt,omitempty"`
    EndsAt       time.Time `json:"endsAt,omitempty"`
    GeneratorURL string    `json:"generatorURL"`
}

I would like to do the sorting on the StartsAt field.

I tried using the sort function but it wasn't available in the email template.

{{ range sort .Alerts.Firing }}

I'm getting

function \"sort\" not defined

Any ideas on how I can get it to sort on StartsAt ?

4

2 回答 2

2

在将警报传递给模板执行之前对其进行排序。这更容易,模板也不应该改变它注定要显示的数据。

例子:

type ByStart []*types.Alert

func (a ByStart) Len() int           { return len(a) }
func (a ByStart) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ByStart) Less(i, j int) bool { return a[i].StartAt.Before(a[j].StartAt) }

func (n *Email) Notify(ctx context.Context, as ...*types.Alert) (bool, error) {
    ...
    sort.Sort(ByStart(as))
    data = n.tmpl.Data(receiverName(ctx), groupLabels(ctx), as...)
    ...
}

编辑:

默认情况下,模板不提供排序功能。您可以注册可以从模板调用的自定义函数,但这必须在解析模板和Go代码(而不是模板文本;请参阅 参考资料Template.Funcs())之前完成。之所以如此,是因为模板必须是可静态分析的,并且在解析模板文本时了解哪些自定义函数是有效的是关键。

仅从模板文本中,没有自定义函数的帮助,您无法实现这一点。

于 2017-01-06T13:00:53.013 回答
-1

在那个 alertmanager电子邮件模板中,我注意到了这一行:

  {{ range .Annotations.SortedPairs }}{{ .Name }} = {{ .Value }}<br />{{ end }}

所以也许你可以尝试:

{{ range .Alerts.Firing.Sorted }}
于 2018-09-27T13:12:33.230 回答