-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathmain.go
120 lines (101 loc) · 2.36 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
package main
import (
"encoding/json"
"fmt"
"log"
"net"
"net/url"
"os"
"text/template"
"time"
"golang.org/x/net/websocket"
)
func init() {
log.SetOutput(os.Stderr)
}
func main() {
c := getConf()
t, err := template.New("template").Funcs(template.FuncMap{
"color": color,
"bColor": bColor,
"noColor": func() string { return color("reset") },
"date": date,
"join": join,
"concat": concat,
"duration": duration,
"int": toInt,
"float": toFloat,
"string": toString,
"get": get,
"column": column,
"begin": begin,
"contain": contain,
"level": level,
}).Parse(c.Pattern)
if err != nil {
log.Fatalf("Failed to parse pattern: %s", err.Error())
}
var u *url.URL
u, err = url.Parse(c.Address)
if err != nil {
log.Fatal(err)
}
// Display filters
if len(c.Match) > 0 {
log.Printf("Filters are:")
for _, f := range c.Match {
if f.Not {
log.Printf(" "+supportedMatchOperatorsMap[f.Operator].descriptionNot, f.Key, f.Value)
} else {
log.Printf(" "+supportedMatchOperatorsMap[f.Operator].description, f.Key, f.Value)
}
}
}
for {
// Try to connect
log.Printf("Connecting to %s...\n", u.Host)
ws, err := websocket.Dial(u.String(), "", "http://mySelf")
if err != nil {
log.Fatal(err)
}
log.Println("Connected!")
var msg []byte
for {
ws.SetReadDeadline(time.Now().Add(5 * time.Second))
err := websocket.Message.Receive(ws, &msg)
if t, ok := err.(net.Error); ok && t.Timeout() {
// Timeout, send a Pong && continue
pingCodec.Send(ws, nil)
continue
}
if err != nil {
log.Printf("Error while reading from %q: %q. Will try to reconnect after 1s...\n", u.Host, err.Error())
time.Sleep(1 * time.Second)
break
}
// Extract Message
var logMessage struct {
Message string `json:"message"`
}
json.Unmarshal(msg, &logMessage)
// Extract infos
var message map[string]interface{}
json.Unmarshal([]byte(logMessage.Message), &message)
if !match(message, c.Match) {
continue
}
if c.Raw {
fmt.Println(string(logMessage.Message))
} else if c.formatFunc != nil {
fmt.Println(c.formatFunc(message))
} else {
// Print them
err = t.Execute(os.Stdout, message)
os.Stdout.Write([]byte{'\n'})
if err != nil {
log.Printf("Error while executing template: %s", err.Error())
}
}
}
}
}