1
0
mirror of https://github.com/astaxie/beego.git synced 2024-06-02 11:33:27 +00:00
Beego/core/logs/jianliao.go

98 lines
2.1 KiB
Go
Raw Normal View History

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-11 13:10:12 +00:00
"github.com/pkg/errors"
2020-07-22 14:50:08 +00:00
)
// JLWriter implements beego LoggerInterface and is used to send jiaoliao webhook
type JLWriter struct {
2020-09-11 13:10:12 +00:00
AuthorName string `json:"authorname"`
Title string `json:"title"`
WebhookURL string `json:"webhookurl"`
RedirectURL string `json:"redirecturl,omitempty"`
ImageURL string `json:"imageurl,omitempty"`
Level int `json:"level"`
formatter LogFormatter
Formatter string `json:"formatter"`
2020-07-22 14:50:08 +00:00
}
2020-08-06 15:07:18 +00:00
// newJLWriter creates jiaoliao writer.
2020-07-22 14:50:08 +00:00
func newJLWriter() Logger {
2020-09-11 13:10:12 +00:00
res := &JLWriter{Level: LevelTrace}
res.formatter = res
return res
2020-07-22 14:50:08 +00:00
}
// Init JLWriter with json config string
2020-09-11 13:10:12 +00:00
func (s *JLWriter) Init(config string) error {
res := json.Unmarshal([]byte(config), s)
if res == nil && len(s.Formatter) > 0 {
fmtr, ok := GetFormatter(s.Formatter)
if !ok {
return errors.New(fmt.Sprintf("the formatter with name: %s not found", s.Formatter))
2020-08-28 17:18:28 +00:00
}
2020-09-11 13:10:12 +00:00
s.formatter = fmtr
2020-08-28 17:18:28 +00:00
}
2020-09-11 13:10:12 +00:00
return res
2020-07-22 14:50:08 +00:00
}
2020-08-20 18:00:35 +00:00
func (s *JLWriter) Format(lm *LogMsg) string {
2020-09-19 15:04:40 +00:00
msg := lm.OldStyleFormat()
msg = fmt.Sprintf("%s %s", lm.When.Format("2006-01-02 15:04:05"), msg)
return msg
2020-09-11 13:10:12 +00:00
}
func (s *JLWriter) SetFormatter(f LogFormatter) {
s.formatter = f
2020-08-20 18:00:35 +00:00
}
2020-08-06 15:07:18 +00:00
// WriteMsg writes message in smtp writer.
// Sends an email with subject and only this message.
func (s *JLWriter) WriteMsg(lm *LogMsg) error {
if lm.Level > s.Level {
2020-07-22 14:50:08 +00:00
return nil
}
2020-09-11 13:10:12 +00:00
text := s.formatter.Format(lm)
2020-08-28 17:18:28 +00:00
2020-07-22 14:50:08 +00:00
form := url.Values{}
form.Add("authorName", s.AuthorName)
form.Add("title", s.Title)
form.Add("text", text)
if s.RedirectURL != "" {
form.Add("redirectUrl", s.RedirectURL)
}
if s.ImageURL != "" {
form.Add("imageUrl", s.ImageURL)
}
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 *JLWriter) Flush() {
}
// Destroy implementing method. empty.
func (s *JLWriter) Destroy() {
}
func init() {
Register(AdapterJianLiao, newJLWriter)
}