/
main.go
131 lines (112 loc) · 2.52 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package main
import (
"bytes"
"crypto/sha1"
"encoding/hex"
"encoding/json"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/chrissnell/syslog"
"github.com/namsral/flag"
)
var (
config = flag.String("config", "", "Config file to read")
bind = flag.String("bind", "0.0.0.0:1514", "Address used to bind the syslog server")
slackURL = flag.String("slack_url", "", "URL of the Slack Incoming Webhook")
)
type handler struct {
*syslog.BaseHandler
}
type notification struct {
Text string `json:"text,omitempty"`
Attachments []*attachment `json:"attachments"`
}
type attachment struct {
Fallback string `json:"fallback,omitempty"`
Pretext string `json:"pretext,omitempty"`
Color string `json:"color,omitempty"`
Fields []*field `json:"fields,omitempty"`
}
type field struct {
Title string `json:"title"`
Value string `json:"value"`
Short bool `json:"short"`
}
func (h *handler) mainLoop() {
for {
m := h.Get()
if m == nil {
break
}
tagsum := sha1.Sum([]byte(m.Tag))
taghex := hex.EncodeToString(tagsum[:])
msg, err := json.Marshal(¬ification{
Attachments: []*attachment{
&attachment{
Fallback: "[" + m.Tag + "] " + m.Content,
Color: "#" + taghex[:6],
Fields: []*field{
&field{
Title: "tag",
Value: m.Tag,
Short: true,
},
&field{
Title: "hostname",
Value: m.Hostname,
Short: true,
},
&field{
Title: "time",
Value: m.Timestamp.Format(time.RFC822Z),
Short: false,
},
&field{
Title: "content",
Value: m.Content,
Short: false,
},
},
},
},
})
if err != nil {
log.Print(err)
}
res, err := http.Post(*slackURL, "application/json", bytes.NewReader(msg))
if err != nil {
log.Print(err)
}
res.Body.Close()
}
log.Print("Exit handler")
h.End()
}
func filter(m *syslog.Message) bool {
return true
}
func newHandler() *handler {
h := &handler{syslog.NewBaseHandler(5, filter, false)}
go h.mainLoop()
return h
}
func main() {
flag.Parse()
s := syslog.NewServer()
s.AddHandler(newHandler())
err := s.Listen(*bind)
if err != nil {
log.Fatal(err)
}
log.Printf("Listening to %s", *bind)
sc := make(chan os.Signal, 2)
signal.Notify(sc, syscall.SIGTERM, syscall.SIGINT)
<-sc
log.Print("Shutdown the server...")
s.Shutdown()
log.Print("Server is down")
}