1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-24 00:50:55 +00:00
Beego/core/logs/slack.go

85 lines
1.9 KiB
Go
Raw Normal View History

2020-07-22 14:50:08 +00:00
package logs
import (
2020-11-09 14:43:49 +00:00
"bytes"
2020-07-22 14:50:08 +00:00
"encoding/json"
"fmt"
"net/http"
2020-08-28 17:00:45 +00:00
2020-09-11 13:10:12 +00:00
"github.com/pkg/errors"
2020-07-22 14:50:08 +00:00
)
// SLACKWriter implements beego LoggerInterface and is used to send jiaoliao webhook
type SLACKWriter struct {
2020-09-11 13:10:12 +00:00
WebhookURL string `json:"webhookurl"`
Level int `json:"level"`
formatter LogFormatter
Formatter string `json:"formatter"`
2020-07-22 14:50:08 +00:00
}
2020-08-06 15:07:18 +00:00
// newSLACKWriter creates jiaoliao writer.
2020-07-22 14:50:08 +00:00
func newSLACKWriter() Logger {
2020-09-11 13:10:12 +00:00
res := &SLACKWriter{Level: LevelTrace}
res.formatter = res
return res
2020-07-22 14:50:08 +00:00
}
2020-08-20 18:00:35 +00:00
func (s *SLACKWriter) Format(lm *LogMsg) string {
2020-11-09 14:43:49 +00:00
// text := fmt.Sprintf("{\"text\": \"%s\"}", msg)
return lm.When.Format("2006-01-02 15:04:05") + " " + lm.OldStyleFormat()
2020-09-11 13:10:12 +00:00
}
func (s *SLACKWriter) SetFormatter(f LogFormatter) {
s.formatter = f
2020-08-20 18:00:35 +00:00
}
2020-07-22 14:50:08 +00:00
// Init SLACKWriter with json config string
2020-09-11 13:10:12 +00:00
func (s *SLACKWriter) Init(config string) error {
res := json.Unmarshal([]byte(config), s)
2020-09-11 13:10:12 +00:00
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
2020-07-22 14:50:08 +00:00
}
// WriteMsg write message in smtp writer.
2020-08-06 15:07:18 +00:00
// Sends an email with subject and only this message.
func (s *SLACKWriter) WriteMsg(lm *LogMsg) error {
if lm.Level > s.Level {
2020-07-22 14:50:08 +00:00
return nil
}
2020-08-20 18:06:51 +00:00
msg := s.Format(lm)
2020-11-09 14:43:49 +00:00
m := make(map[string]string, 1)
m["text"] = msg
2020-07-22 14:50:08 +00:00
2020-11-09 14:43:49 +00:00
body, _ := json.Marshal(m)
// resp, err := http.PostForm(s.WebhookURL, form)
resp, err := http.Post(s.WebhookURL, "application/json", bytes.NewReader(body))
2020-07-22 14:50:08 +00:00
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)
}