2020-07-22 14:50:08 +00:00
|
|
|
package logs
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"net/url"
|
2020-08-28 17:00:45 +00:00
|
|
|
|
2020-09-10 15:31:49 +00:00
|
|
|
"github.com/astaxie/beego/pkg/infrastructure/utils"
|
2020-07-22 14:50:08 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// SLACKWriter implements beego LoggerInterface and is used to send jiaoliao webhook
|
|
|
|
type SLACKWriter struct {
|
2020-08-24 19:22:38 +00:00
|
|
|
WebhookURL string `json:"webhookurl"`
|
|
|
|
Level int `json:"level"`
|
|
|
|
UseCustomFormatter bool
|
|
|
|
CustomFormatter func(*LogMsg) string
|
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 {
|
|
|
|
return &SLACKWriter{Level: LevelTrace}
|
|
|
|
}
|
|
|
|
|
2020-08-20 18:00:35 +00:00
|
|
|
func (s *SLACKWriter) Format(lm *LogMsg) string {
|
|
|
|
return lm.Msg
|
|
|
|
}
|
|
|
|
|
2020-07-22 14:50:08 +00:00
|
|
|
// Init SLACKWriter with json config string
|
2020-09-10 15:31:49 +00:00
|
|
|
func (s *SLACKWriter) Init(jsonConfig string, opts ...utils.KV) error {
|
2020-08-28 17:00:45 +00:00
|
|
|
// if elem != nil {
|
|
|
|
// s.UseCustomFormatter = true
|
|
|
|
// s.CustomFormatter = elem
|
|
|
|
// }
|
|
|
|
// }
|
2020-08-24 19:22:38 +00:00
|
|
|
|
2020-08-28 17:00:45 +00:00
|
|
|
return json.Unmarshal([]byte(jsonConfig), s)
|
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.
|
2020-08-18 20:30:11 +00:00
|
|
|
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)
|
|
|
|
text := fmt.Sprintf("{\"text\": \"%s %s\"}", lm.When.Format("2006-01-02 15:04:05"), 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)
|
|
|
|
}
|