/
slack.go
84 lines (70 loc) · 1.88 KB
/
slack.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
package logs
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"github.com/pkg/errors"
)
// SLACKWriter implements beego LoggerInterface and is used to send jiaoliao webhook
type SLACKWriter struct {
WebhookURL string `json:"webhookurl"`
Level int `json:"level"`
formatter LogFormatter
Formatter string `json:"formatter"`
}
// newSLACKWriter creates jiaoliao writer.
func newSLACKWriter() Logger {
res := &SLACKWriter{Level: LevelTrace}
res.formatter = res
return res
}
func (s *SLACKWriter) Format(lm *LogMsg) string {
// text := fmt.Sprintf("{\"text\": \"%s\"}", msg)
return lm.When.Format("2006-01-02 15:04:05") + " " + lm.OldStyleFormat()
}
func (s *SLACKWriter) SetFormatter(f LogFormatter) {
s.formatter = f
}
// Init SLACKWriter with json config string
func (s *SLACKWriter) Init(config string) error {
res := json.Unmarshal([]byte(config), s)
if res == nil && len(s.Formatter) > 0 {
fmtr, ok := GetFormatter(s.Formatter)
if !ok {
return errors.New(fmt.Sprintf("the formatter with name: %s not found", s.Formatter))
}
s.formatter = fmtr
}
return res
}
// WriteMsg write message in smtp writer.
// Sends an email with subject and only this message.
func (s *SLACKWriter) WriteMsg(lm *LogMsg) error {
if lm.Level > s.Level {
return nil
}
msg := s.Format(lm)
m := make(map[string]string, 1)
m["text"] = msg
body, _ := json.Marshal(m)
// resp, err := http.PostForm(s.WebhookURL, form)
resp, err := http.Post(s.WebhookURL, "application/json", bytes.NewReader(body))
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("Post webhook failed %s %d", resp.Status, resp.StatusCode)
}
return nil
}
// Flush implementing method. empty.
func (s *SLACKWriter) Flush() {
}
// Destroy implementing method. empty.
func (s *SLACKWriter) Destroy() {
}
func init() {
Register(AdapterSlack, newSLACKWriter)
}