高热共公日志库
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.

73 lines
1.6 KiB

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