alert

package
v0.8.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 27 Imported by: 3

README

Alerting Utilities

This package integrates several popular alerting functions, and provides default templates to send notifications.

Supported Channels

There are several channels supported to send notifications, and developers could configure any one or several channels in program.

  • Telegram
  • Dingtalk
  • SMTP
  • Pagerduty
  • Flashduty

Initialize Channel

Before sending any message to notification channels, the client should create a channel robot. To construct a channel robot programmatically:

// Construct a notification channel imperatively
var notifyCh alert.Channel

// DingTalk Channel
notifyCh = alert.NewDingTalkChannel(...)
// or PagerDuty Channel
notifyCh = alert.NewPagerDutyChannel(...)
// or Smtp email Channel
notifyCh = alert.NewSmtpChannel(...)
// or Telegram Channel
notifyCh = alert.NewTelegramChannel(...)

Alternatively, you can initialize the alert channels from configuration file or environment variables, which is recommended.

// Initialize the alert channels from configurations loaded by viper
alert.MustInitFromViper()
// After initialization, you can retrieve the notification channel using a unique channel ID
notifyCh := alert.DefaultManager().Channel(chID)

Send Notification

Once the channel is initialized, you can send a notification message through the channel:

SMTP, FlashDuty and DingTalk use the supplied context for cancellation and do not add a default request timeout. Set a deadline when calling them directly; the example below allows three seconds. The logrus alert hook sets its own SendTimeout. SMTP cancellation covers TCP connection establishment, the TLS handshake, and the entire SMTP session; errors remain identifiable with errors.Is against context.Canceled or context.DeadlineExceeded. Webhook URLs must point directly to the final endpoint; redirects are rejected.

The built-in Telegram formatter preserves Markdown for short notifications. Oversized notifications use a single plain-text message, truncated at a Unicode character boundary with an ellipsis within a conservative 4096 UTF-16-unit limit.

ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()

notifyCh.Send(ctx, &alert.Notification{
    Title:    "Alert testing",
    Severity: alert.SeverityLow,
    Content: `This is a test notification message`,
})

Hook to Logrus

Alert can be integrated with log module, so as to send alerting message when warning or error logs occurred. Generally, developers could initialize log and alert via config.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidNotification = errors.New("invalid notification")
)

Functions

func ErrChannelNotFound added in v0.2.1

func ErrChannelNotFound(ch string) error

func ErrChannelTypeNotSupported added in v0.2.1

func ErrChannelTypeNotSupported(chType string) error

func MustInitFromViper

func MustInitFromViper()

MustInitFromViper inits alert from viper settings or panic on error.

Types

type Channel added in v0.2.1

type Channel interface {
	Name() string
	Type() ChannelType
	Send(context.Context, *Notification) error
}

Notification channel interface.

type ChannelType added in v0.2.1

type ChannelType string

Notification channel type.

const (
	ChannelTypeDingTalk  ChannelType = "dingtalk"
	ChannelTypeTelegram  ChannelType = "telegram"
	ChannelTypeSMTP      ChannelType = "smtp"
	ChannelTypePagerDuty ChannelType = "pagerduty"
	ChannelTypeFlashDuty ChannelType = "flashduty"
)

type DingTalkChannel added in v0.2.1

type DingTalkChannel struct {
	*dingtalk.Robot
	ID        string         // channel id
	Config    DingTalkConfig // channel config
	Formatter Formatter      // message formatter
}

DingTalkChannel DingTalk notification channel

func NewDingTalkChannel added in v0.2.1

func NewDingTalkChannel(chID string, fmt Formatter, conf DingTalkConfig) *DingTalkChannel

func (*DingTalkChannel) Name added in v0.2.1

func (dtc *DingTalkChannel) Name() string

func (*DingTalkChannel) Send added in v0.2.1

func (dtc *DingTalkChannel) Send(ctx context.Context, note *Notification) error

func (*DingTalkChannel) Type added in v0.2.1

func (dtc *DingTalkChannel) Type() ChannelType

type DingTalkConfig

type DingTalkConfig struct {
	AtMobiles []string // mobiles for @ members
	IsAtAll   bool     // whether to @ all members
	Webhook   string   // webhook url
	Secret    string   // secret token
	MsgType   string   `default:"markdown"` // message type: `text` or `markdown`
}

type DingTalkMarkdownFormatter added in v0.2.1

type DingTalkMarkdownFormatter struct {
	// contains filtered or unexported fields
}

func NewDingtalkMarkdownFormatter added in v0.2.1

func NewDingtalkMarkdownFormatter(tags, mentions []string) (*DingTalkMarkdownFormatter, error)

func (DingTalkMarkdownFormatter) Format added in v0.2.1

func (f DingTalkMarkdownFormatter) Format(note *Notification) (string, error)

type FlashDutyChannel added in v0.6.7

type FlashDutyChannel struct {
	*flashduty.Robot
	ID     string          // the identifier of the channel
	Config FlashDutyConfig // the configuration for the FlashDuty channel
}

FlashDutyChannel represents a FlashDuty notification channel.

func NewFlashDutyChannel added in v0.6.7

func NewFlashDutyChannel(chID string, conf FlashDutyConfig) *FlashDutyChannel

NewFlashDutyChannel creates a new FlashDuty channel with the given ID and configuration

func (*FlashDutyChannel) Name added in v0.6.7

func (c *FlashDutyChannel) Name() string

Name returns the ID of the channel

func (*FlashDutyChannel) Send added in v0.6.7

func (c *FlashDutyChannel) Send(ctx context.Context, note *Notification) error

Send sends notification using the FlashDuty channel.

func (*FlashDutyChannel) Type added in v0.6.7

func (c *FlashDutyChannel) Type() ChannelType

Type returns the type of the channel, which is FlashDuty

type FlashDutyConfig added in v0.6.7

type FlashDutyConfig struct {
	Webhook string // webhook url
	Secret  string // secret token
}

type Formatter added in v0.2.1

type Formatter interface {
	Format(note *Notification) (string, error)
}

Formatter defines how messages are formatted.

type Manager added in v0.2.1

type Manager struct {
	// contains filtered or unexported fields
}

func DefaultManager added in v0.2.1

func DefaultManager() *Manager

func NewManager added in v0.2.1

func NewManager() *Manager

func (*Manager) Add added in v0.2.1

func (m *Manager) Add(ch Channel) Channel

func (*Manager) All added in v0.2.1

func (m *Manager) All() (chs []Channel)

func (*Manager) Channel added in v0.2.1

func (m *Manager) Channel(name string) (Channel, bool)

func (*Manager) Del added in v0.2.1

func (m *Manager) Del(name string)

type Notification added in v0.2.1

type Notification struct {
	Title    string      // message title
	Content  interface{} // message content
	Severity Severity    // severity level
}

Notification represents core information for an alert.

type PagerDutyChannel added in v0.3.0

type PagerDutyChannel struct {
	*pagerduty.Client
	ID     string          // the identifier of the channel
	Config PagerDutyConfig // the configuration for the PagerDuty channel
	// contains filtered or unexported fields
}

PagerDutyChannel represents a PagerDuty notification channel.

func NewPagerDutyChannel added in v0.3.0

func NewPagerDutyChannel(chID string, tags []string, conf PagerDutyConfig) *PagerDutyChannel

NewPagerDutyChannel creates a new PagerDuty channel with the given ID and configuration

func (*PagerDutyChannel) Name added in v0.3.0

func (c *PagerDutyChannel) Name() string

Name returns the ID of the channel

func (*PagerDutyChannel) Send added in v0.3.0

func (c *PagerDutyChannel) Send(ctx context.Context, note *Notification) error

Send sends notification using the PagerDuty channel.

func (*PagerDutyChannel) Type added in v0.3.0

func (c *PagerDutyChannel) Type() ChannelType

Type returns the type of the channel, which is PagerDuty

type PagerDutyConfig added in v0.3.0

type PagerDutyConfig struct {
	// The auth token for the PagerDuty service.
	AuthToken string
	// The routinng key for the service integration.
	RoutingKey string
	// The unique location of the affected system, preferably a hostname or FQDN.
	Source string
}

type Severity added in v0.2.1

type Severity int

Alert severity level.

const (
	SeverityLow Severity = iota
	SeverityMedium
	SeverityHigh
	SeverityCritical
)

func (Severity) String added in v0.2.1

func (s Severity) String() string

type SimpleTextFormatter added in v0.2.1

type SimpleTextFormatter struct {
	// contains filtered or unexported fields
}

func NewSimpleTextFormatter added in v0.2.1

func NewSimpleTextFormatter(tags, mentions []string) (fmt *SimpleTextFormatter, err error)

func (*SimpleTextFormatter) Format added in v0.2.1

func (f *SimpleTextFormatter) Format(note *Notification) (string, error)

type SmtpChannel added in v0.2.1

type SmtpChannel struct {
	Formatter Formatter  // Formatter is used to format the notification message
	ID        string     // ID is the identifier of the channel
	Config    SmtpConfig // Config contains the configuration for the SMTP server
}

SmtpChannel represents a SMTP email notification channel

func NewSmtpChannel added in v0.2.1

func NewSmtpChannel(chID string, fmtter Formatter, conf SmtpConfig) *SmtpChannel

NewSmtpChannel creates a new SMTP channel with the given ID, formatter, and configuration

func (*SmtpChannel) Name added in v0.2.1

func (c *SmtpChannel) Name() string

Name returns the ID of the channel

func (*SmtpChannel) Send added in v0.2.1

func (c *SmtpChannel) Send(ctx context.Context, note *Notification) error

Send sends a notification using the SMTP channel

func (*SmtpChannel) SendProtoMsg added in v0.3.0

func (c *SmtpChannel) SendProtoMsg(ctx context.Context, msg string) error

SendProtoMsg sends protocol message using the SMTP channel. Callers should provide a context with a deadline to bound the entire session.

func (*SmtpChannel) Type added in v0.2.1

func (c *SmtpChannel) Type() ChannelType

Type returns the type of the channel, which is SMTP

type SmtpConfig added in v0.2.1

type SmtpConfig struct {
	Host     string   // SMTP endpoint and port
	From     string   // Sender address
	To       []string // Receipt addresses
	Password string   // SMTP password
}

type SmtpHtmlFormatter added in v0.2.1

type SmtpHtmlFormatter struct {
	// contains filtered or unexported fields
}

func NewSmtpHtmlFormatter added in v0.2.1

func NewSmtpHtmlFormatter(
	conf SmtpConfig, tags []string) (f *SmtpHtmlFormatter, err error)

func (*SmtpHtmlFormatter) Format added in v0.2.1

func (f *SmtpHtmlFormatter) Format(note *Notification) (msg string, err error)

Format builds an HTML email and rejects titles containing CR or LF to prevent the title from introducing additional email headers.

type TelegramChannel added in v0.2.1

type TelegramChannel struct {
	*bot.Bot
	Formatter Formatter      // message formatter
	ID        string         // channel id
	Config    TelegramConfig // channel config
}

TelegramChannel Telegram notification channel

func NewTelegramChannel added in v0.2.1

func NewTelegramChannel(chID string, fmt Formatter, conf TelegramConfig) (*TelegramChannel, error)

func (*TelegramChannel) Name added in v0.2.1

func (tc *TelegramChannel) Name() string

func (*TelegramChannel) Send added in v0.2.1

func (tc *TelegramChannel) Send(ctx context.Context, note *Notification) error

func (*TelegramChannel) Type added in v0.2.1

func (tc *TelegramChannel) Type() ChannelType

type TelegramConfig added in v0.2.1

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

type TelegramMarkdownFormatter added in v0.2.1

type TelegramMarkdownFormatter struct {
	// contains filtered or unexported fields
}

func NewTelegramMarkdownFormatter added in v0.2.1

func NewTelegramMarkdownFormatter(tags, atUsers []string) (f *TelegramMarkdownFormatter, err error)

func (*TelegramMarkdownFormatter) Format added in v0.2.1

func (f *TelegramMarkdownFormatter) Format(note *Notification) (string, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址