diff --git a/README.md b/README.md index ad6e543..58ca80a 100644 --- a/README.md +++ b/README.md @@ -31,5 +31,18 @@ open-falcon alarm 发送消息组件,注意这个是基于2.0版本新增的im - 告警时间: {{.Time}} - 告警说明: {{.Desc}} - 次数:{{.Count}} +- 表达式中的连续次数 {{.TriggerCount}} -**如果参数配置错误会导致模板渲染失败无法发送。** \ No newline at end of file +**如果参数配置错误会导致模板渲染失败无法发送。** + +默认模板中有如下表达式: + +```text +{{with elapse .Count 60 .TriggerCount 300}}{{divide . 60}}{{end}} +``` + +其中 60 是数据上报周期,默认是60s,如果修改了默认值,需要修改这里的值。 + +300 是告警之间推迟时间,默认5分钟。 + +{{divide . 60}} 是除以60s,得到分钟 \ No newline at end of file diff --git a/config/config.go b/config/config.go index 65a48ae..8194f0f 100644 --- a/config/config.go +++ b/config/config.go @@ -4,6 +4,7 @@ import ( "encoding/json" "io/ioutil" "log" + "time" ) // Config 配置 @@ -32,7 +33,7 @@ type AlarmMessage struct { Tags string // tags TriggerCount int // 间隔 Count int // 当前告警次数 - Time string + Time time.Time Expression string // 告警时间 } diff --git a/main.go b/main.go index e355072..22a34d8 100644 --- a/main.go +++ b/main.go @@ -57,7 +57,12 @@ func main() { // 第一次,直接返回上报间隔 return reportInterval * triggerCount }, "divide": func(a, b int) int { return a / b }, - "timeFormat": func(t time.Time, format string) string { return t.Format(format) }} + "timeFormat": func(t time.Time, format string) string { + return t.Format(format) + }, + "timeDiffFormat": func(t time.Time, format string, seconds int) string { + return t.Add(-(time.Second * time.Duration(seconds))).Format(format) + }} tpl = template.Must(template.New(path.Base(cfg.DingTalk.TemplateFile)).Funcs(funcMap).ParseFiles(cfg.DingTalk.TemplateFile)) if cfg.DingTalk.Enable { diff --git a/message-template.md b/message-template.md index 09842ae..ee08e93 100644 --- a/message-template.md +++ b/message-template.md @@ -5,6 +5,7 @@ - 告警指标: {{.Counter}} {{.Tags}} - 表达式: {{.Expression}} - 告警主机: {{.Endpoint}} -- 告警时间: {{.Time}} +- 通知时间: {{timeFormat .Time "2006-01-02 15:04:05"}} +- 告警时间: {{elapse .Count 60 .TriggerCount 300 | timeDiffFormat .Time "2006-01-02 15:04:05"}} - 当前次数: {{.Count}} - 告警说明: {{.Desc}},已持续 {{with elapse .Count 60 .TriggerCount 300}}{{divide . 60}}{{end}}分钟 diff --git a/util/util.go b/util/util.go index e7ad20e..266c5c9 100644 --- a/util/util.go +++ b/util/util.go @@ -9,6 +9,7 @@ import ( "regexp" "strconv" "strings" + "time" ) // EncodeJSON json序列化(禁止 html 符号转义) @@ -72,7 +73,11 @@ func HandleContent(content string) (*config.AlarmMessage, error) { if err != nil { return nil, err } - time := strings.Join(subArgs[1:], " ") + timeStr := strings.Join(subArgs[1:], " ") + t, err := time.Parse("2006-01-02 15:04:05", timeStr) + if err != nil { + return nil, err + } return &config.AlarmMessage{Level: args[0], Type: args[1], Endpoint: args[2], Expression: expression, - Desc: desc, Counter: counter, Tags: tags, TriggerCount: triggerCount, Count: count, Time: time}, nil + Desc: desc, Counter: counter, Tags: tags, TriggerCount: triggerCount, Count: count, Time: t}, nil }