-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsns.go
101 lines (79 loc) · 2.26 KB
/
sns.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package logrus_sns
import (
"encoding/json"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sns"
"github.com/sirupsen/logrus"
)
// SNSHook is a logrus Hook for dispatching messages to the specified topics on AWS SNS
type SNSHook struct {
// Messages with a log level not contained in this array
// will not be dispatched. If nil, all messages will be dispatched.
AcceptedLevels []logrus.Level
Session *sns.SNS
TopicArn *string
Subject *string
Extra map[string]interface{}
}
// Levels define the level of logs which will be sent to SNS
func (hook *SNSHook) Levels() []logrus.Level {
if hook.AcceptedLevels == nil {
return logrus.AllLevels
}
return hook.AcceptedLevels
}
func NewSNSHook(topicArn, subject, region string) (*SNSHook, error) {
s, err := session.NewSession(&aws.Config{
Region: aws.String(region),
})
hook, err := NewSNSHookWithSession(topicArn, subject, s)
if err != nil {
return nil, err
}
return hook, nil
}
func NewSNSHookWithSession(topicArn, subject string, s *session.Session) (*SNSHook, error) {
// Creates a SNS hook with a custom AWS session
hook := &SNSHook{}
hook.Session = sns.New(s)
_, err := hook.Session.GetTopicAttributes(&sns.GetTopicAttributesInput{
TopicArn: aws.String(topicArn),
})
if err != nil {
return nil, err
}
hook.TopicArn = aws.String(topicArn)
hook.Subject = aws.String(subject)
return hook, nil
}
func (hook *SNSHook) Fire(entry *logrus.Entry) error {
publishInput := sns.PublishInput{}
publishInput.TopicArn = hook.TopicArn
publishInput.Message = &entry.Message
publishInput.Subject = hook.Subject
data, err := json.Marshal(&entry.Data)
if err != nil {
return fmt.Errorf("failed to serialize log data into JSON: %s", err.Error())
}
publishInput.MessageAttributes = map[string]*sns.MessageAttributeValue{
"Level": {
DataType: aws.String("String"),
StringValue: aws.String(entry.Level.String()),
},
"Time": {
DataType: aws.String("String"),
StringValue: aws.String(entry.Time.String()),
},
"Data": {
DataType: aws.String("String"),
StringValue: aws.String(string(data)),
},
}
_, err = hook.Session.Publish(&publishInput)
if err != nil {
return err
}
return nil
}