forked from pkallberg/cx
/
stacks-listen.go
116 lines (97 loc) · 2.16 KB
/
stacks-listen.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
package main
import (
"encoding/json"
"fmt"
"os"
"os/signal"
"strconv"
"syscall"
"time"
"github.com/cloud66/cli"
"github.com/cloud66/cloud66"
"github.com/cloud66/wray"
"github.com/mgutz/ansi"
)
type logMessage struct {
Severity int `json:"severity"`
Message string `json:"message"`
Time time.Time `json:"time"`
Raw bool `json:"is_raw"`
Deployment bool `json:"is_cap"`
}
type tailHandler struct {
totalMessages int
messagesShown int
}
func runListen(c *cli.Context) {
stack := mustStack(c)
StartListen(stack)
}
func StartListen(stack *cloud66.Stack) {
if debugMode {
fmt.Printf("Connecting to Faye on %s\n", fayeEndpoint)
}
// sigChan := make(chan os.Signal, 1)
// signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
channel := "/realtime/" + stack.Uid + "/*"
wray.RegisterTransports([]wray.Transport{&wray.HttpTransport{}})
fc := wray.NewFayeClient(fayeEndpoint)
sub := fc.Subscribe(channel, true, handleMessage)
if debugMode {
fmt.Printf("Subscribed to %s\n", sub)
}
go fc.Listen()
// handle interrupts
hupChan := make(chan os.Signal, 1)
termChan := make(chan os.Signal, 1)
signal.Notify(hupChan, syscall.SIGHUP)
signal.Notify(termChan, syscall.SIGINT, syscall.SIGTERM)
for {
select {
case <-termChan:
return
case <-hupChan:
return
}
}
}
func handleMessage(msg wray.Message) {
redColor := ansi.ColorFunc("red+h")
capColor := ansi.ColorFunc("yellow")
infoColor := ansi.ColorFunc("white")
s, err := strconv.Unquote(msg.Data)
if err != nil {
fmt.Println("Error: ", err)
}
var m logMessage
err = json.Unmarshal([]byte(s), &m)
if err != nil {
fmt.Println("Error:", err)
}
var level string
var colorFunc func(string) string
switch m.Severity {
case 0:
level = "TRACE"
colorFunc = infoColor
case 1:
level = "DEBUG"
colorFunc = infoColor
case 2:
level = "INFO"
colorFunc = infoColor
case 3:
level = "WARN"
colorFunc = capColor
case 4:
level = "ERROR"
colorFunc = redColor
case 5:
level = "IMPORTANT"
colorFunc = redColor
case 6:
level = "FATAL"
colorFunc = redColor
}
fmt.Println(colorFunc(fmt.Sprintf("%s [%s] - %s", m.Time, level, m.Message)))
}