Alerting: refactor notifiers to use package specific Logger interface (#60361)

* introduce Logger interface local to channles + implementaton that wraps the Grafana logger
* make NewFactoryConfig accept LoggerFactory
* add logger field to FactoryConfig
* update usages of log.Logger to internal interface
This commit is contained in:
Yuri Tseretyan 2022-12-15 11:10:31 -05:00 committed by GitHub
parent 0fb9987d12
commit 6637333748
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
48 changed files with 157 additions and 108 deletions

View File

@ -111,7 +111,9 @@ func (e *EmbeddedContactPoint) Valid(decryptFunc channels.GetDecryptedValueFn) e
cfg, _ := channels.NewFactoryConfig(&channels.NotificationChannelConfig{
Settings: e.Settings,
Type: e.Type,
}, nil, decryptFunc, nil, nil)
}, nil, decryptFunc, nil, nil, func(ctx ...interface{}) channels.Logger {
return &channels.FakeLogger{}
})
if _, err := factory(cfg); err != nil {
return err
}

View File

@ -514,7 +514,7 @@ func (am *Alertmanager) buildReceiverIntegration(r *apimodels.PostableGrafanaRec
SecureSettings: secureSettings,
}
)
factoryConfig, err := channels.NewFactoryConfig(cfg, NewNotificationSender(am.NotificationService), am.decryptFn, tmpl, newImageStore(am.Store))
factoryConfig, err := channels.NewFactoryConfig(cfg, NewNotificationSender(am.NotificationService), am.decryptFn, tmpl, newImageStore(am.Store), LoggerFactory)
if err != nil {
return nil, InvalidReceiverError{
Receiver: r,

View File

@ -11,8 +11,6 @@ import (
"github.com/prometheus/alertmanager/template"
"github.com/prometheus/alertmanager/types"
"github.com/prometheus/common/model"
"github.com/grafana/grafana/pkg/infra/log"
)
// GetDecryptedValueFn is a function that returns the decrypted value of
@ -63,18 +61,18 @@ func AlertmanagerFactory(fc FactoryConfig) (NotificationChannel, error) {
Cfg: *fc.Config,
}
}
return NewAlertmanagerNotifier(config, fc.ImageStore, nil, fc.DecryptFunc), nil
return NewAlertmanagerNotifier(config, fc.Logger, fc.ImageStore, nil, fc.DecryptFunc), nil
}
// NewAlertmanagerNotifier returns a new Alertmanager notifier.
func NewAlertmanagerNotifier(config *AlertmanagerConfig, images ImageStore, _ *template.Template, fn GetDecryptedValueFn) *AlertmanagerNotifier {
func NewAlertmanagerNotifier(config *AlertmanagerConfig, l Logger, images ImageStore, _ *template.Template, fn GetDecryptedValueFn) *AlertmanagerNotifier {
return &AlertmanagerNotifier{
Base: NewBase(config.NotificationChannelConfig),
images: images,
urls: config.URLs,
basicAuthUser: config.BasicAuthUser,
basicAuthPassword: config.BasicAuthPassword,
logger: log.New("alerting.notifier.prometheus-alertmanager"),
logger: l,
}
}
@ -86,7 +84,7 @@ type AlertmanagerNotifier struct {
urls []*url.URL
basicAuthUser string
basicAuthPassword string
logger log.Logger
logger Logger
}
// Notify sends alert notifications to Alertmanager.

View File

@ -8,7 +8,6 @@ import (
"testing"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/secrets/fakes"
secretsManager "github.com/grafana/grafana/pkg/services/secrets/manager"
@ -66,7 +65,7 @@ func TestNewAlertmanagerNotifier(t *testing.T) {
return
}
require.NoError(t, err)
sn := NewAlertmanagerNotifier(cfg, &UnavailableImageStore{}, tmpl, decryptFn)
sn := NewAlertmanagerNotifier(cfg, &FakeLogger{}, &UnavailableImageStore{}, tmpl, decryptFn)
require.NotNil(t, sn)
})
}
@ -159,13 +158,13 @@ func TestAlertmanagerNotifier_Notify(t *testing.T) {
decryptFn := secretsService.GetDecryptedValue
cfg, err := NewAlertmanagerConfig(m, decryptFn)
require.NoError(t, err)
sn := NewAlertmanagerNotifier(cfg, images, tmpl, decryptFn)
sn := NewAlertmanagerNotifier(cfg, &FakeLogger{}, images, tmpl, decryptFn)
var body []byte
origSendHTTPRequest := sendHTTPRequest
t.Cleanup(func() {
sendHTTPRequest = origSendHTTPRequest
})
sendHTTPRequest = func(ctx context.Context, url *url.URL, cfg httpCfg, logger log.Logger) ([]byte, error) {
sendHTTPRequest = func(ctx context.Context, url *url.URL, cfg httpCfg, logger Logger) ([]byte, error) {
body = cfg.body
return nil, c.sendHTTPRequestError
}

View File

@ -7,7 +7,6 @@ import (
"testing"
"time"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/prometheus/alertmanager/template"
"github.com/prometheus/alertmanager/types"
"github.com/prometheus/common/model"
@ -76,7 +75,7 @@ func TestDefaultTemplateString(t *testing.T) {
tmpl.ExternalURL = externalURL
var tmplErr error
l := log.New("default-template-test")
l := &FakeLogger{}
expand, _ := TmplText(context.Background(), tmpl, alerts, l, &tmplErr)
cases := []struct {

View File

@ -9,8 +9,6 @@ import (
"github.com/prometheus/alertmanager/template"
"github.com/prometheus/alertmanager/types"
"github.com/grafana/grafana/pkg/infra/log"
)
const defaultDingdingMsgType = "link"
@ -54,7 +52,7 @@ func newDingDingNotifier(fc FactoryConfig) (*DingDingNotifier, error) {
}
return &DingDingNotifier{
Base: NewBase(fc.Config),
log: log.New("alerting.notifier.dingding"),
log: fc.Logger,
ns: fc.NotificationService,
tmpl: fc.Template,
settings: *settings,
@ -64,7 +62,7 @@ func newDingDingNotifier(fc FactoryConfig) (*DingDingNotifier, error) {
// DingDingNotifier is responsible for sending alert notifications to ding ding.
type DingDingNotifier struct {
*Base
log log.Logger
log Logger
ns WebhookSender
tmpl *template.Template
settings dingDingSettings

View File

@ -179,6 +179,7 @@ func TestDingdingNotifier(t *testing.T) {
// TODO: allow changing the associated values for different tests.
NotificationService: webhookSender,
Template: tmpl,
Logger: &FakeLogger{},
}
pn, err := newDingDingNotifier(fc)
if c.expInitError != "" {

View File

@ -17,13 +17,12 @@ import (
"github.com/prometheus/common/model"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/setting"
)
type DiscordNotifier struct {
*Base
log log.Logger
log Logger
ns WebhookSender
images ImageStore
tmpl *template.Template
@ -67,7 +66,7 @@ func newDiscordNotifier(fc FactoryConfig) (*DiscordNotifier, error) {
return &DiscordNotifier{
Base: NewBase(fc.Config),
log: log.New("alerting.notifier.discord"),
log: fc.Logger,
ns: fc.NotificationService,
images: fc.ImageStore,
tmpl: fc.Template,

View File

@ -302,6 +302,7 @@ func TestDiscordNotifier(t *testing.T) {
// TODO: allow changing the associated values for different tests.
NotificationService: webhookSender,
Template: tmpl,
Logger: &FakeLogger{},
}
dn, err := newDiscordNotifier(fc)

View File

@ -11,7 +11,6 @@ import (
"github.com/prometheus/alertmanager/template"
"github.com/prometheus/alertmanager/types"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/util"
)
@ -23,7 +22,7 @@ type EmailNotifier struct {
SingleEmail bool
Message string
Subject string
log log.Logger
log Logger
ns EmailSender
images ImageStore
tmpl *template.Template
@ -45,7 +44,7 @@ func EmailFactory(fc FactoryConfig) (NotificationChannel, error) {
Cfg: *fc.Config,
}
}
return NewEmailNotifier(cfg, fc.NotificationService, fc.ImageStore, fc.Template), nil
return NewEmailNotifier(cfg, fc.Logger, fc.NotificationService, fc.ImageStore, fc.Template), nil
}
func NewEmailConfig(config *NotificationChannelConfig) (*EmailConfig, error) {
@ -66,14 +65,14 @@ func NewEmailConfig(config *NotificationChannelConfig) (*EmailConfig, error) {
// NewEmailNotifier is the constructor function
// for the EmailNotifier.
func NewEmailNotifier(config *EmailConfig, ns EmailSender, images ImageStore, t *template.Template) *EmailNotifier {
func NewEmailNotifier(config *EmailConfig, l Logger, ns EmailSender, images ImageStore, t *template.Template) *EmailNotifier {
return &EmailNotifier{
Base: NewBase(config.NotificationChannelConfig),
Addresses: config.Addresses,
SingleEmail: config.SingleEmail,
Message: config.Message,
Subject: config.Subject,
log: log.New("alerting.notifier.email"),
log: l,
ns: ns,
images: images,
tmpl: t,

View File

@ -50,7 +50,7 @@ func TestEmailNotifier(t *testing.T) {
Settings: settingsJSON,
})
require.NoError(t, err)
emailNotifier := NewEmailNotifier(cfg, emailSender, &UnavailableImageStore{}, tmpl)
emailNotifier := NewEmailNotifier(cfg, &FakeLogger{}, emailSender, &UnavailableImageStore{}, tmpl)
alerts := []*types.Alert{
{
@ -290,7 +290,7 @@ func createSut(t *testing.T, messageTmpl string, subjectTmpl string, emailTmpl *
Settings: settingsJSON,
})
require.NoError(t, err)
emailNotifier := NewEmailNotifier(cfg, ns, &UnavailableImageStore{}, emailTmpl)
emailNotifier := NewEmailNotifier(cfg, &FakeLogger{}, ns, &UnavailableImageStore{}, emailTmpl)
return emailNotifier
}

View File

@ -14,10 +14,11 @@ type FactoryConfig struct {
ImageStore ImageStore
// Used to retrieve image URLs for messages, or data for uploads.
Template *template.Template
Logger Logger
}
func NewFactoryConfig(config *NotificationChannelConfig, notificationService NotificationSender,
decryptFunc GetDecryptedValueFn, template *template.Template, imageStore ImageStore) (FactoryConfig, error) {
decryptFunc GetDecryptedValueFn, template *template.Template, imageStore ImageStore, loggerFactory LoggerFactory) (FactoryConfig, error) {
if config.Settings == nil {
return FactoryConfig{}, errors.New("no settings supplied")
}
@ -36,6 +37,7 @@ func NewFactoryConfig(config *NotificationChannelConfig, notificationService Not
DecryptFunc: decryptFunc,
Template: template,
ImageStore: imageStore,
Logger: loggerFactory("ngalert.notifier." + config.Type),
}, nil
}

View File

@ -11,7 +11,6 @@ import (
"github.com/prometheus/alertmanager/template"
"github.com/prometheus/alertmanager/types"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/setting"
)
@ -19,7 +18,7 @@ import (
// alert notifications to Google chat.
type GoogleChatNotifier struct {
*Base
log log.Logger
log Logger
ns WebhookSender
images ImageStore
tmpl *template.Template
@ -57,7 +56,7 @@ func newGoogleChatNotifier(fc FactoryConfig) (*GoogleChatNotifier, error) {
return &GoogleChatNotifier{
Base: NewBase(fc.Config),
log: log.New("alerting.notifier.googlechat"),
log: fc.Logger,
ns: fc.NotificationService,
images: fc.ImageStore,
tmpl: fc.Template,

View File

@ -477,6 +477,7 @@ func TestGoogleChatNotifier(t *testing.T) {
ImageStore: imageStore,
NotificationService: webhookSender,
Template: tmpl,
Logger: &FakeLogger{},
}
pn, err := newGoogleChatNotifier(fc)

View File

@ -11,7 +11,6 @@ import (
"github.com/prometheus/common/model"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/models"
)
@ -19,7 +18,7 @@ import (
// alert notifications to Kafka.
type KafkaNotifier struct {
*Base
log log.Logger
log Logger
images ImageStore
ns WebhookSender
tmpl *template.Template
@ -59,7 +58,7 @@ func newKafkaNotifier(fc FactoryConfig) (*KafkaNotifier, error) {
return &KafkaNotifier{
Base: NewBase(fc.Config),
log: log.New("alerting.notifier.kafka"),
log: fc.Logger,
images: fc.ImageStore,
ns: fc.NotificationService,
tmpl: fc.Template,
@ -151,7 +150,7 @@ func buildState(as ...*types.Alert) models.AlertStateType {
return models.AlertStateAlerting
}
func buildContextImages(ctx context.Context, l log.Logger, imageStore ImageStore, as ...*types.Alert) []interface{} {
func buildContextImages(ctx context.Context, l Logger, imageStore ImageStore, as ...*types.Alert) []interface{} {
var contexts []interface{}
_ = withStoredImages(ctx, l, imageStore,
func(_ int, image Image) error {

View File

@ -128,6 +128,7 @@ func TestKafkaNotifier(t *testing.T) {
NotificationService: webhookSender,
DecryptFunc: nil,
Template: tmpl,
Logger: &FakeLogger{},
}
pn, err := newKafkaNotifier(fc)

View File

@ -9,8 +9,6 @@ import (
"github.com/prometheus/alertmanager/template"
"github.com/prometheus/alertmanager/types"
"github.com/grafana/grafana/pkg/infra/log"
)
var (
@ -21,7 +19,7 @@ var (
// alert notifications to LINE.
type LineNotifier struct {
*Base
log log.Logger
log Logger
ns WebhookSender
tmpl *template.Template
settings lineSettings
@ -55,7 +53,7 @@ func newLineNotifier(fc FactoryConfig) (*LineNotifier, error) {
return &LineNotifier{
Base: NewBase(fc.Config),
log: log.New("alerting.notifier.line"),
log: fc.Logger,
ns: fc.NotificationService,
tmpl: fc.Template,
settings: lineSettings{token: token, title: title, description: description},

View File

@ -114,6 +114,7 @@ func TestLineNotifier(t *testing.T) {
NotificationService: webhookSender,
DecryptFunc: decryptFn,
Template: tmpl,
Logger: &FakeLogger{},
}
pn, err := newLineNotifier(fc)
if c.expInitError != "" {

View File

@ -0,0 +1,45 @@
package channels
type LoggerFactory func(ctx ...interface{}) Logger
type Logger interface {
// New returns a new contextual Logger that has this logger's context plus the given context.
New(ctx ...interface{}) Logger
Log(keyvals ...interface{}) error
// Debug logs a message with debug level and key/value pairs, if any.
Debug(msg string, ctx ...interface{})
// Info logs a message with info level and key/value pairs, if any.
Info(msg string, ctx ...interface{})
// Warn logs a message with warning level and key/value pairs, if any.
Warn(msg string, ctx ...interface{})
// Error logs a message with error level and key/value pairs, if any.
Error(msg string, ctx ...interface{})
}
type FakeLogger struct {
}
func (f FakeLogger) New(ctx ...interface{}) Logger {
return f
}
func (f FakeLogger) Log(keyvals ...interface{}) error {
return nil
}
func (f FakeLogger) Debug(msg string, ctx ...interface{}) {
}
func (f FakeLogger) Info(msg string, ctx ...interface{}) {
}
func (f FakeLogger) Warn(msg string, ctx ...interface{}) {
}
func (f FakeLogger) Error(msg string, ctx ...interface{}) {
}

View File

@ -14,8 +14,6 @@ import (
"github.com/prometheus/alertmanager/types"
"github.com/prometheus/common/model"
ptr "github.com/xorcare/pointer"
"github.com/grafana/grafana/pkg/infra/log"
)
const (
@ -35,7 +33,7 @@ var (
type OpsgenieNotifier struct {
*Base
tmpl *template.Template
log log.Logger
log Logger
ns WebhookSender
images ImageStore
settings *opsgenieSettings
@ -126,7 +124,7 @@ func NewOpsgenieNotifier(fc FactoryConfig) (*OpsgenieNotifier, error) {
return &OpsgenieNotifier{
Base: NewBase(fc.Config),
tmpl: fc.Template,
log: log.New("alerting.notifier.opsgenie"),
log: fc.Logger,
ns: fc.NotificationService,
images: fc.ImageStore,
settings: settings,

View File

@ -250,6 +250,7 @@ func TestOpsgenieNotifier(t *testing.T) {
DecryptFunc: decryptFn,
ImageStore: &UnavailableImageStore{},
Template: tmpl,
Logger: &FakeLogger{},
}
ctx := notify.WithGroupKey(context.Background(), "alertname")

View File

@ -12,8 +12,6 @@ import (
"github.com/prometheus/alertmanager/template"
"github.com/prometheus/alertmanager/types"
"github.com/prometheus/common/model"
"github.com/grafana/grafana/pkg/infra/log"
)
const (
@ -41,7 +39,7 @@ var (
type PagerdutyNotifier struct {
*Base
tmpl *template.Template
log log.Logger
log Logger
ns WebhookSender
images ImageStore
settings *pagerdutySettings
@ -131,7 +129,7 @@ func newPagerdutyNotifier(fc FactoryConfig) (*PagerdutyNotifier, error) {
return &PagerdutyNotifier{
Base: NewBase(fc.Config),
tmpl: fc.Template,
log: log.New("alerting.notifier." + fc.Config.Name),
log: fc.Logger,
ns: fc.NotificationService,
images: fc.ImageStore,
settings: settings,

View File

@ -293,6 +293,7 @@ func TestPagerdutyNotifier(t *testing.T) {
NotificationService: webhookSender,
DecryptFunc: decryptFn,
Template: tmpl,
Logger: &FakeLogger{},
}
pn, err := newPagerdutyNotifier(fc)
if c.expInitError != "" {

View File

@ -16,8 +16,6 @@ import (
"github.com/prometheus/alertmanager/template"
"github.com/prometheus/alertmanager/types"
"github.com/prometheus/common/model"
"github.com/grafana/grafana/pkg/infra/log"
)
const (
@ -39,7 +37,7 @@ var (
type PushoverNotifier struct {
*Base
tmpl *template.Template
log log.Logger
log Logger
images ImageStore
ns WebhookSender
settings pushoverSettings
@ -148,7 +146,7 @@ func NewPushoverNotifier(fc FactoryConfig) (*PushoverNotifier, error) {
return &PushoverNotifier{
Base: NewBase(fc.Config),
tmpl: fc.Template,
log: log.New("alerting.notifier.pushover"),
log: fc.Logger,
images: fc.ImageStore,
ns: fc.NotificationService,
settings: settings,

View File

@ -229,6 +229,7 @@ func TestPushoverNotifier(t *testing.T) {
NotificationService: webhookSender,
DecryptFunc: decryptFn,
Template: tmpl,
Logger: &FakeLogger{},
}
pn, err := NewPushoverNotifier(fc)

View File

@ -10,13 +10,11 @@ import (
"github.com/prometheus/alertmanager/template"
"github.com/prometheus/alertmanager/types"
"github.com/prometheus/common/model"
"github.com/grafana/grafana/pkg/infra/log"
)
type SensuGoNotifier struct {
*Base
log log.Logger
log Logger
images ImageStore
ns WebhookSender
tmpl *template.Template
@ -71,7 +69,7 @@ func NewSensuGoNotifier(fc FactoryConfig) (*SensuGoNotifier, error) {
}
return &SensuGoNotifier{
Base: NewBase(fc.Config),
log: log.New("alerting.notifier.sensugo"),
log: fc.Logger,
images: fc.ImageStore,
ns: fc.NotificationService,
tmpl: fc.Template,

View File

@ -158,6 +158,7 @@ func TestSensuGoNotifier(t *testing.T) {
NotificationService: webhookSender,
Template: tmpl,
DecryptFunc: decryptFn,
Logger: &FakeLogger{},
}
sn, err := NewSensuGoNotifier(fc)

View File

@ -22,7 +22,6 @@ import (
"github.com/prometheus/alertmanager/template"
"github.com/prometheus/alertmanager/types"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/setting"
)
@ -52,7 +51,7 @@ var (
var SlackAPIEndpoint = "https://slack.com/api/chat.postMessage"
type sendFunc func(ctx context.Context, req *http.Request, logger log.Logger) (string, error)
type sendFunc func(ctx context.Context, req *http.Request, logger Logger) (string, error)
// https://api.slack.com/reference/messaging/attachments#legacy_fields - 1024, no units given, assuming runes or characters.
const slackMaxTitleLenRunes = 1024
@ -61,7 +60,7 @@ const slackMaxTitleLenRunes = 1024
// alert notification to Slack.
type SlackNotifier struct {
*Base
log log.Logger
log Logger
tmpl *template.Template
images ImageStore
webhookSender WebhookSender
@ -161,7 +160,7 @@ func buildSlackNotifier(factoryConfig FactoryConfig) (*SlackNotifier, error) {
images: factoryConfig.ImageStore,
webhookSender: factoryConfig.NotificationService,
sendFn: sendSlackRequest,
log: log.New("alerting.notifier.slack"),
log: factoryConfig.Logger,
tmpl: factoryConfig.Template,
}, nil
}
@ -238,7 +237,7 @@ func (sn *SlackNotifier) Notify(ctx context.Context, alerts ...*types.Alert) (bo
// sendSlackRequest sends a request to the Slack API.
// Stubbable by tests.
var sendSlackRequest = func(ctx context.Context, req *http.Request, logger log.Logger) (string, error) {
var sendSlackRequest = func(ctx context.Context, req *http.Request, logger Logger) (string, error) {
resp, err := slackClient.Do(req)
if err != nil {
return "", fmt.Errorf("failed to send request: %w", err)
@ -270,7 +269,7 @@ var sendSlackRequest = func(ctx context.Context, req *http.Request, logger log.L
}
}
func handleSlackIncomingWebhookResponse(resp *http.Response, logger log.Logger) (string, error) {
func handleSlackIncomingWebhookResponse(resp *http.Response, logger Logger) (string, error) {
b, err := io.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("failed to read response: %w", err)
@ -314,7 +313,7 @@ func handleSlackIncomingWebhookResponse(resp *http.Response, logger log.Logger)
return "", fmt.Errorf("failed incoming webhook: %s", string(b))
}
func handleSlackJSONResponse(resp *http.Response, logger log.Logger) (string, error) {
func handleSlackJSONResponse(resp *http.Response, logger Logger) (string, error) {
b, err := io.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("failed to read response: %w", err)

View File

@ -20,7 +20,6 @@ import (
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/secrets/fakes"
secretsManager "github.com/grafana/grafana/pkg/services/secrets/manager"
"github.com/grafana/grafana/pkg/setting"
@ -379,7 +378,7 @@ type slackRequestRecorder struct {
requests []*http.Request
}
func (s *slackRequestRecorder) fn(_ context.Context, r *http.Request, _ log.Logger) (string, error) {
func (s *slackRequestRecorder) fn(_ context.Context, r *http.Request, _ Logger) (string, error) {
s.requests = append(s.requests, r)
return "", nil
}
@ -441,6 +440,7 @@ func setupSlackForTests(t *testing.T, settings string) (*SlackNotifier, *slackRe
NotificationService: notificationService,
DecryptFunc: secretsService.GetDecryptedValue,
Template: tmpl,
Logger: &FakeLogger{},
}
sn, err := buildSlackNotifier(c)
@ -568,7 +568,7 @@ func TestSendSlackRequest(t *testing.T) {
req, err := http.NewRequest(http.MethodGet, server.URL, nil)
require.NoError(tt, err)
_, err = sendSlackRequest(context.Background(), req, log.New("test"))
_, err = sendSlackRequest(context.Background(), req, &FakeLogger{})
if !test.expectError {
require.NoError(tt, err)
} else {

View File

@ -10,8 +10,6 @@ import (
"github.com/prometheus/alertmanager/template"
"github.com/prometheus/alertmanager/types"
"github.com/prometheus/common/model"
"github.com/grafana/grafana/pkg/infra/log"
)
const (
@ -249,7 +247,7 @@ func buildTeamsSettings(fc FactoryConfig) (teamsSettings, error) {
type TeamsNotifier struct {
*Base
tmpl *template.Template
log log.Logger
log Logger
ns WebhookSender
images ImageStore
settings teamsSettings
@ -263,7 +261,7 @@ func NewTeamsNotifier(fc FactoryConfig) (*TeamsNotifier, error) {
}
return &TeamsNotifier{
Base: NewBase(fc.Config),
log: log.New("alerting.notifier.teams"),
log: fc.Logger,
ns: fc.NotificationService,
images: fc.ImageStore,
tmpl: fc.Template,

View File

@ -265,6 +265,7 @@ func TestTeamsNotifier(t *testing.T) {
ImageStore: &UnavailableImageStore{},
NotificationService: webhookSender,
Template: tmpl,
Logger: &FakeLogger{},
}
pn, err := NewTeamsNotifier(fc)

View File

@ -13,8 +13,6 @@ import (
"github.com/prometheus/alertmanager/notify"
"github.com/prometheus/alertmanager/template"
"github.com/prometheus/alertmanager/types"
"github.com/grafana/grafana/pkg/infra/log"
)
var (
@ -33,7 +31,7 @@ const telegramMaxMessageLenRunes = 4096
// alert notifications to Telegram.
type TelegramNotifier struct {
*Base
log log.Logger
log Logger
images ImageStore
ns WebhookSender
tmpl *template.Template
@ -102,7 +100,7 @@ func NewTelegramNotifier(fc FactoryConfig) (*TelegramNotifier, error) {
return &TelegramNotifier{
Base: NewBase(fc.Config),
tmpl: fc.Template,
log: log.New("alerting.notifier.telegram"),
log: fc.Logger,
images: fc.ImageStore,
ns: fc.NotificationService,
settings: settings,

View File

@ -135,6 +135,7 @@ func TestTelegramNotifier(t *testing.T) {
NotificationService: notificationService,
DecryptFunc: decryptFn,
Template: tmpl,
Logger: &FakeLogger{},
}
n, err := NewTelegramNotifier(fc)

View File

@ -14,7 +14,6 @@ import (
"github.com/prometheus/alertmanager/types"
"github.com/prometheus/common/model"
"github.com/grafana/grafana/pkg/infra/log"
ngmodels "github.com/grafana/grafana/pkg/services/ngalert/models"
)
@ -58,7 +57,7 @@ func removePrivateItems(kv template.KV) template.KV {
return kv
}
func extendAlert(alert template.Alert, externalURL string, logger log.Logger) *ExtendedAlert {
func extendAlert(alert template.Alert, externalURL string, logger Logger) *ExtendedAlert {
// remove "private" annotations & labels so they don't show up in the template
extended := &ExtendedAlert{
Status: alert.Status,
@ -150,7 +149,7 @@ func setOrgIdQueryParam(url *url.URL, orgId string) string {
return url.String()
}
func ExtendData(data *template.Data, logger log.Logger) *ExtendedData {
func ExtendData(data *template.Data, logger Logger) *ExtendedData {
alerts := []ExtendedAlert{}
for _, alert := range data.Alerts {
@ -171,7 +170,7 @@ func ExtendData(data *template.Data, logger log.Logger) *ExtendedData {
return extended
}
func TmplText(ctx context.Context, tmpl *template.Template, alerts []*types.Alert, l log.Logger, tmplErr *error) (func(string) string, *ExtendedData) {
func TmplText(ctx context.Context, tmpl *template.Template, alerts []*types.Alert, l Logger, tmplErr *error) (func(string) string, *ExtendedData) {
promTmplData := notify.GetTemplateData(ctx, tmpl, alerts, l)
data := ExtendData(promTmplData, l)

View File

@ -11,8 +11,6 @@ import (
"github.com/prometheus/alertmanager/template"
"github.com/prometheus/alertmanager/types"
"github.com/prometheus/common/model"
"github.com/grafana/grafana/pkg/infra/log"
)
var (
@ -23,7 +21,7 @@ var (
// alert notifications to Threema.
type ThreemaNotifier struct {
*Base
log log.Logger
log Logger
images ImageStore
ns WebhookSender
tmpl *template.Template
@ -95,7 +93,7 @@ func NewThreemaNotifier(fc FactoryConfig) (*ThreemaNotifier, error) {
}
return &ThreemaNotifier{
Base: NewBase(fc.Config),
log: log.New("alerting.notifier.threema"),
log: fc.Logger,
images: fc.ImageStore,
ns: fc.NotificationService,
tmpl: fc.Template,

View File

@ -135,6 +135,7 @@ func TestThreemaNotifier(t *testing.T) {
ImageStore: images,
Template: tmpl,
DecryptFunc: secretsService.GetDecryptedValue,
Logger: &FakeLogger{},
}
pn, err := NewThreemaNotifier(fc)

View File

@ -22,7 +22,6 @@ import (
"github.com/prometheus/common/model"
"gopkg.in/yaml.v3"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/ngalert/models"
"github.com/grafana/grafana/pkg/util"
@ -53,7 +52,7 @@ type forEachImageFunc func(index int, image Image) error
// getImage returns the image for the alert or an error. It returns a nil
// image if the alert does not have an image token or the image does not exist.
func getImage(ctx context.Context, l log.Logger, imageStore ImageStore, alert types.Alert) (*Image, error) {
func getImage(ctx context.Context, l Logger, imageStore ImageStore, alert types.Alert) (*Image, error) {
token := getTokenFromAnnotations(alert.Annotations)
if token == "" {
return nil, nil
@ -80,7 +79,7 @@ func getImage(ctx context.Context, l log.Logger, imageStore ImageStore, alert ty
// the error and not iterate the remaining alerts. A forEachFunc can return ErrImagesDone
// to stop the iteration of remaining alerts if the intended image or maximum number of
// images have been found.
func withStoredImages(ctx context.Context, l log.Logger, imageStore ImageStore, forEachFunc forEachImageFunc, alerts ...*types.Alert) error {
func withStoredImages(ctx context.Context, l Logger, imageStore ImageStore, forEachFunc forEachImageFunc, alerts ...*types.Alert) error {
for index, alert := range alerts {
logger := l.New("alert", alert.String())
img, err := getImage(ctx, logger, imageStore, *alert)
@ -195,7 +194,7 @@ type httpCfg struct {
// sendHTTPRequest sends an HTTP request.
// Stubbable by tests.
var sendHTTPRequest = func(ctx context.Context, url *url.URL, cfg httpCfg, logger log.Logger) ([]byte, error) {
var sendHTTPRequest = func(ctx context.Context, url *url.URL, cfg httpCfg, logger Logger) ([]byte, error) {
var reader io.Reader
if len(cfg.body) > 0 {
reader = bytes.NewReader(cfg.body)
@ -249,7 +248,7 @@ var sendHTTPRequest = func(ctx context.Context, url *url.URL, cfg httpCfg, logge
return respBody, nil
}
func joinUrlPath(base, additionalPath string, logger log.Logger) string {
func joinUrlPath(base, additionalPath string, logger Logger) string {
u, err := url.Parse(base)
if err != nil {
logger.Debug("failed to parse URL while joining URL", "url", base, "error", err.Error())

View File

@ -10,7 +10,6 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/ngalert/models"
)
@ -45,7 +44,7 @@ func TestWithStoredImages(t *testing.T) {
)
// should iterate all images
err = withStoredImages(ctx, log.New(ctx), imageStore, func(index int, image Image) error {
err = withStoredImages(ctx, &FakeLogger{}, imageStore, func(index int, image Image) error {
i += 1
return nil
}, alerts...)
@ -54,7 +53,7 @@ func TestWithStoredImages(t *testing.T) {
// should iterate just the first image
i = 0
err = withStoredImages(ctx, log.New(ctx), imageStore, func(index int, image Image) error {
err = withStoredImages(ctx, &FakeLogger{}, imageStore, func(index int, image Image) error {
i += 1
return ErrImagesDone
}, alerts...)

View File

@ -13,7 +13,6 @@ import (
"github.com/prometheus/alertmanager/types"
"github.com/prometheus/common/model"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/setting"
)
@ -76,7 +75,7 @@ func NewVictoropsNotifier(fc FactoryConfig) (*VictoropsNotifier, error) {
}
return &VictoropsNotifier{
Base: NewBase(fc.Config),
log: log.New("alerting.notifier.victorops"),
log: fc.Logger,
images: fc.ImageStore,
ns: fc.NotificationService,
tmpl: fc.Template,
@ -89,7 +88,7 @@ func NewVictoropsNotifier(fc FactoryConfig) (*VictoropsNotifier, error) {
// Victorops specifications (http://victorops.force.com/knowledgebase/articles/Integration/Alert-Ingestion-API-Documentation/)
type VictoropsNotifier struct {
*Base
log log.Logger
log Logger
images ImageStore
ns WebhookSender
tmpl *template.Template
@ -169,7 +168,7 @@ func (vn *VictoropsNotifier) SendResolved() bool {
return !vn.GetDisableResolveMessage()
}
func buildMessageType(l log.Logger, tmpl func(string) string, msgType string, as ...*types.Alert) string {
func buildMessageType(l Logger, tmpl func(string) string, msgType string, as ...*types.Alert) string {
if types.Alerts(as...).Status() == model.AlertResolved {
return victoropsAlertStateRecovery
}

View File

@ -204,6 +204,7 @@ func TestVictoropsNotifier(t *testing.T) {
NotificationService: webhookSender,
ImageStore: images,
Template: tmpl,
Logger: &FakeLogger{},
}
pn, err := NewVictoropsNotifier(fc)

View File

@ -9,8 +9,6 @@ import (
"github.com/prometheus/alertmanager/template"
"github.com/prometheus/alertmanager/types"
"github.com/grafana/grafana/pkg/infra/log"
)
const webexAPIURL = "https://webexapis.com/v1/messages"
@ -19,7 +17,7 @@ const webexAPIURL = "https://webexapis.com/v1/messages"
type WebexNotifier struct {
*Base
ns WebhookSender
log log.Logger
log Logger
images ImageStore
tmpl *template.Template
orgID int64
@ -80,12 +78,10 @@ func buildWebexNotifier(factoryConfig FactoryConfig) (*WebexNotifier, error) {
return nil, err
}
logger := log.New("alerting.notifier.webex")
return &WebexNotifier{
Base: NewBase(factoryConfig.Config),
orgID: factoryConfig.Config.OrgID,
log: logger,
log: factoryConfig.Logger,
ns: factoryConfig.NotificationService,
images: factoryConfig.ImageStore,
tmpl: factoryConfig.Template,

View File

@ -124,6 +124,7 @@ func TestWebexNotifier(t *testing.T) {
NotificationService: notificationService,
DecryptFunc: decryptFn,
Template: tmpl,
Logger: &FakeLogger{},
}
n, err := buildWebexNotifier(fc)

View File

@ -13,7 +13,6 @@ import (
"github.com/prometheus/alertmanager/types"
"github.com/prometheus/common/model"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/models"
)
@ -21,7 +20,7 @@ import (
// alert notifications as webhooks.
type WebhookNotifier struct {
*Base
log log.Logger
log Logger
ns WebhookSender
images ImageStore
tmpl *template.Template
@ -118,7 +117,7 @@ func buildWebhookNotifier(factoryConfig FactoryConfig) (*WebhookNotifier, error)
return &WebhookNotifier{
Base: NewBase(factoryConfig.Config),
orgID: factoryConfig.Config.OrgID,
log: log.New("alerting.notifier.webhook"),
log: factoryConfig.Logger,
ns: factoryConfig.NotificationService,
images: factoryConfig.ImageStore,
tmpl: factoryConfig.Template,

View File

@ -358,6 +358,7 @@ func TestWebhookNotifier(t *testing.T) {
DecryptFunc: secretsService.GetDecryptedValue,
ImageStore: &UnavailableImageStore{},
Template: tmpl,
Logger: &FakeLogger{},
}
pn, err := buildWebhookNotifier(fc)

View File

@ -11,8 +11,6 @@ import (
"github.com/prometheus/alertmanager/template"
"github.com/prometheus/alertmanager/types"
"golang.org/x/sync/singleflight"
"github.com/grafana/grafana/pkg/infra/log"
)
var weComEndpoint = "https://qyapi.weixin.qq.com"
@ -111,7 +109,7 @@ func buildWecomNotifier(factoryConfig FactoryConfig) (*WeComNotifier, error) {
return &WeComNotifier{
Base: NewBase(factoryConfig.Config),
tmpl: factoryConfig.Template,
log: log.New("alerting.notifier.wecom"),
log: factoryConfig.Logger,
ns: factoryConfig.NotificationService,
settings: settings,
}, nil
@ -121,7 +119,7 @@ func buildWecomNotifier(factoryConfig FactoryConfig) (*WeComNotifier, error) {
type WeComNotifier struct {
*Base
tmpl *template.Template
log log.Logger
log Logger
ns WebhookSender
settings wecomSettings
tok *WeComAccessToken

View File

@ -177,6 +177,7 @@ func TestWeComNotifier(t *testing.T) {
DecryptFunc: secretsService.GetDecryptedValue,
ImageStore: nil,
Template: tmpl,
Logger: &FakeLogger{},
}
pn, err := buildWecomNotifier(fc)
@ -362,6 +363,7 @@ func TestWeComNotifierAPIAPP(t *testing.T) {
DecryptFunc: secretsService.GetDecryptedValue,
ImageStore: nil,
Template: tmpl,
Logger: &FakeLogger{},
}
pn, err := buildWecomNotifier(fc)
@ -547,6 +549,7 @@ func TestWeComFactory(t *testing.T) {
NotificationService: webhookSender,
DecryptFunc: secretsService.GetDecryptedValue,
ImageStore: nil,
Logger: &FakeLogger{},
}
_, err = WeComFactory(fc)

View File

@ -0,0 +1,18 @@
package notifier
import (
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/services/ngalert/notifier/channels"
)
var LoggerFactory channels.LoggerFactory = func(ctx ...interface{}) channels.Logger {
return &logWrapper{log.New(ctx...)}
}
type logWrapper struct {
*log.ConcreteLogger
}
func (l logWrapper) New(ctx ...interface{}) channels.Logger {
return logWrapper{l.ConcreteLogger.New(ctx...)}
}

View File

@ -500,7 +500,9 @@ func (m *migration) validateAlertmanagerConfig(orgID int64, config *PostableUser
if !exists {
return fmt.Errorf("notifier %s is not supported", gr.Type)
}
factoryConfig, err := channels.NewFactoryConfig(cfg, nil, decryptFunc, nil, nil)
factoryConfig, err := channels.NewFactoryConfig(cfg, nil, decryptFunc, nil, nil, func(ctx ...interface{}) channels.Logger {
return &channels.FakeLogger{}
})
if err != nil {
return err
}