Skip to content

Commit

Permalink
Add support of user mentions for telegram alerting (#52)
Browse files Browse the repository at this point in the history
- Also truncate the alert message and add three tail dots if too long.
  • Loading branch information
wanliqun committed Aug 12, 2024
1 parent 6c749d7 commit e8f88f7
Show file tree
Hide file tree
Showing 6 changed files with 45 additions and 11 deletions.
9 changes: 8 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ Generally, system shall not report failure if auto resolved in a short time. How
Provides utilities to hook middlewares to HTTP handler, e.g. remote address, API key and rate limit.

## Log
We recommend initializing the log module from a configuration file or environment variables. Additionally, you can configure the alert hook to set up default notification channels for sending alert messages when `warning` or `error` logs occur.
We recommend initializing the log module from a configuration file or environment variables.

```go
// Initialize logging by specifying configurations
Expand All @@ -151,6 +151,13 @@ log.MustInit(conf)
log.MustInitFromViper()
```

Additionally, you can configure the alert hook to set up default notification channels for sending alert messages when `warning` or `error` logs occur. You can also customize notifications by specifying the target channel(s) through the `@channel` field in a Logrus entry.

```go
// Send alert to the 'tgrobot' channel instead.
logrus.WithField("@channel": "tgrobot").Warn("Some warning occurred")
```

### ErrorTolerantLogger
`ErrorTolerantLogger` is a thread-safe logger that incorporates error tolerance behavior based on the continuous error count.

Expand Down
23 changes: 20 additions & 3 deletions alert/formatter.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ import (
"github.com/sirupsen/logrus"
)

const (
maxAlertMsgLength = 1024 // max length for the alert message
)

// Formatter defines how messages are formatted.
type Formatter interface {
Format(note *Notification) (string, error)
Expand Down Expand Up @@ -183,10 +187,12 @@ type TelegramMarkdownFormatter struct {
*markdownFormatter
}

func NewTelegramMarkdownFormatter(tags []string) (f *TelegramMarkdownFormatter, err error) {
func NewTelegramMarkdownFormatter(tags, atUsers []string) (f *TelegramMarkdownFormatter, err error) {
funcMap := template.FuncMap{
"escapeMarkdown": escapeMarkdown,
"formatRFC3339": formatRFC3339,
"escapeMarkdown": escapeMarkdown,
"formatRFC3339": formatRFC3339,
"truncateStringWithTail": truncateStringWithTail,
"mentions": func() []string { return atUsers },
}
mf, err := newMarkdownFormatter(
tags, funcMap, telegramMarkdownTemplates[0], telegramMarkdownTemplates[1],
Expand All @@ -202,6 +208,17 @@ func escapeMarkdown(v interface{}) string {
return bot.EscapeMarkdown(fmt.Sprintf("%v", v))
}

// truncateStringWithTail is used to immediately truncate the input string to the max length limit.
// A tail "..." is then added to the end of the string, if the string was longer than max length.
func truncateStringWithTail(s string) string {
if len(s) > maxAlertMsgLength {
// Ttrim the string and add "..."
return s[:maxAlertMsgLength] + "..."
}

return s
}

type htmlFormatter struct {
*tplFormatter
}
Expand Down
7 changes: 4 additions & 3 deletions alert/telegram.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@ var (
)

type TelegramConfig struct {
ApiToken string // Api token
ChatId string // Chat ID
ApiToken string // Api token
ChatId string // Chat ID
AtUsers []string // Mention users
}

// TelegramChannel Telegram notification channel
Expand All @@ -26,7 +27,7 @@ type TelegramChannel struct {
}

func NewTelegramChannel(chID string, fmt Formatter, conf TelegramConfig) (*TelegramChannel, error) {
bot, err := bot.New(conf.ApiToken)
bot, err := bot.New(conf.ApiToken, bot.WithSkipGetMe())
if err != nil {
return nil, err
}
Expand Down
8 changes: 5 additions & 3 deletions alert/templates.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,21 +74,23 @@ Reason
*Tags*: {{.Tags | escapeMarkdown}}
*Severity*: {{.Severity | escapeMarkdown}}
*Time*: {{.Time | formatRFC3339 | escapeMarkdown}}
*{{.Content | escapeMarkdown}}*
*{{.Content | truncateStringWithTail | escapeMarkdown}}*
{{ range mentions }}@{{ . }} {{ end }}
`,
`{{- /* logrus entry markdown template */ -}}
*{{.Level | escapeMarkdown}}*
*Tags*: {{.Tags | escapeMarkdown}}
*Time*: {{.Time | formatRFC3339 | escapeMarkdown}}
*Message*
{{.Msg | escapeMarkdown}}
{{.Msg | truncateStringWithTail | escapeMarkdown}}
{{with .Error}}*Reason*
{{.Error | escapeMarkdown}}
{{else}}{{ end }}{{ if .CtxFields }}*Context Fields*:{{ range $Key, $Val := .CtxFields }}
*{{$Key | escapeMarkdown}}*: {{$Val | escapeMarkdown}}{{ end }}{{ end }}
*{{$Key | escapeMarkdown}}*: {{$Val | truncateStringWithTail | escapeMarkdown}}{{ end }}{{ end }}
{{ range mentions }}@{{ . }} {{ end }}
`,
}

Expand Down
7 changes: 6 additions & 1 deletion alert/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,17 @@ func parseAlertChannel(chID string, chmap map[string]interface{}, tags []string)

return NewDingTalkChannel(chID, fmt, dtconf), nil
case ChannelTypeTelegram:
if toStr, ok := chmap["atusers"].(string); ok {
mentions := strings.Split(toStr, ",")
chmap["atusers"] = mentions
}

var tgconf TelegramConfig
if err := decodeChannelConfig(chmap, &tgconf); err != nil {
return nil, err
}

fmt, err := NewTelegramMarkdownFormatter(tags)
fmt, err := NewTelegramMarkdownFormatter(tags, tgconf.AtUsers)
if err != nil {
return nil, err
}
Expand Down
2 changes: 2 additions & 0 deletions config/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@
# apiToken: ${your_api_token}
# # The chat ID for the Telegram chat where the alerts are sent.
# chatId: ${your_chat_id}
# # List of public usernames in the chat to be mentioned.
# atUsers: []

# # Example configuration for the SMTP (TLS/SSL only) email channel
# smtpbot:
Expand Down

0 comments on commit e8f88f7

Please sign in to comment.