slack.go 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. // Copyright 2017 Unknwon
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License"): you may
  4. // not use this file except in compliance with the License. You may obtain
  5. // a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  11. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  12. // License for the specific language governing permissions and limitations
  13. // under the License.
  14. package clog
  15. import (
  16. "bytes"
  17. "encoding/json"
  18. "errors"
  19. "fmt"
  20. "io/ioutil"
  21. "net/http"
  22. )
  23. type slackAttachment struct {
  24. Text string `json:"text"`
  25. Color string `json:"color"`
  26. }
  27. type slackPayload struct {
  28. Attachments []slackAttachment `json:"attachments"`
  29. }
  30. const (
  31. SLACK = "slack"
  32. )
  33. var slackColors = []string{
  34. "", // Trace
  35. "#3aa3e3", // Info
  36. "warning", // Warn
  37. "danger", // Error
  38. "#ff0200", // Fatal
  39. }
  40. type SlackConfig struct {
  41. // Minimum level of messages to be processed.
  42. Level LEVEL
  43. // Buffer size defines how many messages can be queued before hangs.
  44. BufferSize int64
  45. // Slack webhook URL.
  46. URL string
  47. }
  48. type slack struct {
  49. Adapter
  50. url string
  51. }
  52. func newSlack() Logger {
  53. return &slack{
  54. Adapter: Adapter{
  55. quitChan: make(chan struct{}),
  56. },
  57. }
  58. }
  59. func (s *slack) Level() LEVEL { return s.level }
  60. func (s *slack) Init(v interface{}) error {
  61. cfg, ok := v.(SlackConfig)
  62. if !ok {
  63. return ErrConfigObject{"SlackConfig", v}
  64. }
  65. if !isValidLevel(cfg.Level) {
  66. return ErrInvalidLevel{}
  67. }
  68. s.level = cfg.Level
  69. if len(cfg.URL) == 0 {
  70. return errors.New("URL cannot be empty")
  71. }
  72. s.url = cfg.URL
  73. s.msgChan = make(chan *Message, cfg.BufferSize)
  74. return nil
  75. }
  76. func (s *slack) ExchangeChans(errorChan chan<- error) chan *Message {
  77. s.errorChan = errorChan
  78. return s.msgChan
  79. }
  80. func buildSlackPayload(msg *Message) (string, error) {
  81. payload := slackPayload{
  82. Attachments: []slackAttachment{
  83. {
  84. Text: msg.Body,
  85. Color: slackColors[msg.Level],
  86. },
  87. },
  88. }
  89. p, err := json.Marshal(&payload)
  90. if err != nil {
  91. return "", err
  92. }
  93. return string(p), nil
  94. }
  95. func (s *slack) write(msg *Message) {
  96. payload, err := buildSlackPayload(msg)
  97. if err != nil {
  98. s.errorChan <- fmt.Errorf("slack.buildSlackPayload: %v", err)
  99. return
  100. }
  101. resp, err := http.Post(s.url, "application/json", bytes.NewReader([]byte(payload)))
  102. if err != nil {
  103. s.errorChan <- fmt.Errorf("slack: %v", err)
  104. }
  105. defer resp.Body.Close()
  106. if resp.StatusCode/100 != 2 {
  107. data, _ := ioutil.ReadAll(resp.Body)
  108. s.errorChan <- fmt.Errorf("slack: %s", data)
  109. }
  110. }
  111. func (s *slack) Start() {
  112. LOOP:
  113. for {
  114. select {
  115. case msg := <-s.msgChan:
  116. s.write(msg)
  117. case <-s.quitChan:
  118. break LOOP
  119. }
  120. }
  121. for {
  122. if len(s.msgChan) == 0 {
  123. break
  124. }
  125. s.write(<-s.msgChan)
  126. }
  127. s.quitChan <- struct{}{} // Notify the cleanup is done.
  128. }
  129. func (s *slack) Destroy() {
  130. s.quitChan <- struct{}{}
  131. <-s.quitChan
  132. close(s.msgChan)
  133. close(s.quitChan)
  134. }
  135. func init() {
  136. Register(SLACK, newSlack)
  137. }