高热共公日志库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.3 KiB

  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. return json.Unmarshal([]byte(jsonconfig), s)
  21. }
  22. // WriteMsg write message in smtp writer.
  23. // it will send an email with subject and only this message.
  24. func (s *SLACKWriter) WriteMsg(when time.Time, msg string, level int) error {
  25. if level > s.Level {
  26. return nil
  27. }
  28. text := fmt.Sprintf("{\"text\": \"%s %s\"}", when.Format("2006-01-02 15:04:05"), msg)
  29. form := url.Values{}
  30. form.Add("payload", text)
  31. resp, err := http.PostForm(s.WebhookURL, form)
  32. if err != nil {
  33. return err
  34. }
  35. defer resp.Body.Close()
  36. if resp.StatusCode != http.StatusOK {
  37. return fmt.Errorf("Post webhook failed %s %d", resp.Status, resp.StatusCode)
  38. }
  39. return nil
  40. }
  41. // Flush implementing method. empty.
  42. func (s *SLACKWriter) Flush() {
  43. }
  44. // Destroy implementing method. empty.
  45. func (s *SLACKWriter) Destroy() {
  46. }
  47. func init() {
  48. Register(AdapterSlack, newSLACKWriter)
  49. }