slack.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package logs
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "net/url"
  7. "time"
  8. )
  9. // SLACKWriter implements beego LoggerInterface and is used to send jiaoliao webhook
  10. type SLACKWriter struct {
  11. WebhookURL string `json:"webhookurl"`
  12. Level int `json:"level"`
  13. }
  14. // newSLACKWriter create jiaoliao writer.
  15. func newSLACKWriter() Logger {
  16. return &SLACKWriter{Level: LevelTrace}
  17. }
  18. // Init SLACKWriter with json config string
  19. func (s *SLACKWriter) Init(jsonconfig string) error {
  20. err := json.Unmarshal([]byte(jsonconfig), s)
  21. if err != nil {
  22. return err
  23. }
  24. return nil
  25. }
  26. // WriteMsg write message in smtp writer.
  27. // it will send an email with subject and only this message.
  28. func (s *SLACKWriter) WriteMsg(when time.Time, msg string, level int) error {
  29. if level > s.Level {
  30. return nil
  31. }
  32. text := fmt.Sprintf("{\"text\": \"%s %s\"}", when.Format("2006-01-02 15:04:05"), msg)
  33. form := url.Values{}
  34. form.Add("payload", text)
  35. resp, err := http.PostForm(s.WebhookURL, form)
  36. if err != nil {
  37. return err
  38. }
  39. defer resp.Body.Close()
  40. if resp.StatusCode != http.StatusOK {
  41. return fmt.Errorf("Post webhook failed %s %d", resp.Status, resp.StatusCode)
  42. }
  43. return nil
  44. }
  45. // Flush implementing method. empty.
  46. func (s *SLACKWriter) Flush() {
  47. return
  48. }
  49. // Destroy implementing method. empty.
  50. func (s *SLACKWriter) Destroy() {
  51. return
  52. }
  53. func init() {
  54. Register(AdapterSlack, newSLACKWriter)
  55. }