1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-25 13:10:55 +00:00
Beego/pkg/infrastructure/logs/slack.go

60 lines
1.3 KiB
Go
Raw Normal View History

2020-07-22 14:50:08 +00:00
package logs
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
)
// SLACKWriter implements beego LoggerInterface and is used to send jiaoliao webhook
type SLACKWriter struct {
WebhookURL string `json:"webhookurl"`
Level int `json:"level"`
}
2020-08-06 15:07:18 +00:00
// newSLACKWriter creates jiaoliao writer.
2020-07-22 14:50:08 +00:00
func newSLACKWriter() Logger {
return &SLACKWriter{Level: LevelTrace}
}
// Init SLACKWriter with json config string
func (s *SLACKWriter) Init(jsonconfig string) error {
return json.Unmarshal([]byte(jsonconfig), s)
}
// 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
}
text := fmt.Sprintf("{\"text\": \"%s %s\"}", lm.When.Format("2006-01-02 15:04:05"), lm.Msg)
2020-07-22 14:50:08 +00:00
form := url.Values{}
form.Add("payload", text)
resp, err := http.PostForm(s.WebhookURL, form)
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)
}