slack.go 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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. var slackColors = []string{
  31. "", // Trace
  32. "#3aa3e3", // Info
  33. "warning", // Warn
  34. "danger", // Error
  35. "#ff0200", // Fatal
  36. }
  37. type SlackConfig struct {
  38. // Minimum level of messages to be processed.
  39. Level LEVEL
  40. // Buffer size defines how many messages can be queued before hangs.
  41. BufferSize int64
  42. // Slack webhook URL.
  43. URL string
  44. }
  45. type slack struct {
  46. Adapter
  47. url string
  48. }
  49. func newSlack() Logger {
  50. return &slack{
  51. Adapter: Adapter{
  52. quitChan: make(chan struct{}),
  53. },
  54. }
  55. }
  56. func (s *slack) Level() LEVEL { return s.level }
  57. func (s *slack) Init(v interface{}) error {
  58. cfg, ok := v.(SlackConfig)
  59. if !ok {
  60. return ErrConfigObject{"SlackConfig", v}
  61. }
  62. if !isValidLevel(cfg.Level) {
  63. return ErrInvalidLevel{}
  64. }
  65. s.level = cfg.Level
  66. if len(cfg.URL) == 0 {
  67. return errors.New("URL cannot be empty")
  68. }
  69. s.url = cfg.URL
  70. s.msgChan = make(chan *Message, cfg.BufferSize)
  71. return nil
  72. }
  73. func (s *slack) ExchangeChans(errorChan chan<- error) chan *Message {
  74. s.errorChan = errorChan
  75. return s.msgChan
  76. }
  77. func buildSlackPayload(msg *Message) (string, error) {
  78. payload := slackPayload{
  79. Attachments: []slackAttachment{
  80. {
  81. Text: msg.Body,
  82. Color: slackColors[msg.Level],
  83. },
  84. },
  85. }
  86. p, err := json.Marshal(&payload)
  87. if err != nil {
  88. return "", err
  89. }
  90. return string(p), nil
  91. }
  92. func (s *slack) write(msg *Message) {
  93. payload, err := buildSlackPayload(msg)
  94. if err != nil {
  95. s.errorChan <- fmt.Errorf("slack: buildSlackPayload: %v", err)
  96. return
  97. }
  98. resp, err := http.Post(s.url, "application/json", bytes.NewReader([]byte(payload)))
  99. if err != nil {
  100. s.errorChan <- fmt.Errorf("slack: %v", err)
  101. return
  102. }
  103. defer resp.Body.Close()
  104. if resp.StatusCode/100 != 2 {
  105. data, _ := ioutil.ReadAll(resp.Body)
  106. s.errorChan <- fmt.Errorf("slack: %s", data)
  107. }
  108. }
  109. func (s *slack) Start() {
  110. LOOP:
  111. for {
  112. select {
  113. case msg := <-s.msgChan:
  114. s.write(msg)
  115. case <-s.quitChan:
  116. break LOOP
  117. }
  118. }
  119. for {
  120. if len(s.msgChan) == 0 {
  121. break
  122. }
  123. s.write(<-s.msgChan)
  124. }
  125. s.quitChan <- struct{}{} // Notify the cleanup is done.
  126. }
  127. func (s *slack) Destroy() {
  128. s.quitChan <- struct{}{}
  129. <-s.quitChan
  130. close(s.msgChan)
  131. close(s.quitChan)
  132. }
  133. func init() {
  134. Register(SLACK, newSlack)
  135. }