forked from looplab/logspout-logstash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logstash.go
91 lines (79 loc) · 2.15 KB
/
logstash.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
package logstash
import (
"encoding/json"
"errors"
"log"
"net"
"github.com/gliderlabs/logspout/router"
)
func init() {
router.AdapterFactories.Register(NewLogstashAdapter, "logstash")
}
// LogstashAdapter is an adapter that streams UDP JSON to Logstash.
type LogstashAdapter struct {
conn net.Conn
route *router.Route
}
// NewLogstashAdapter creates a LogstashAdapter with UDP as the default transport.
func NewLogstashAdapter(route *router.Route) (router.LogAdapter, error) {
transport, found := router.AdapterTransports.Lookup(route.AdapterTransport("udp"))
if !found {
return nil, errors.New("unable to find adapter: " + route.Adapter)
}
conn, err := transport.Dial(route.Address, route.Options)
if err != nil {
return nil, err
}
return &LogstashAdapter{
route: route,
conn: conn,
}, nil
}
// Stream implements the router.LogAdapter interface.
func (a *LogstashAdapter) Stream(logstream chan *router.Message) {
for m := range logstream {
dockerInfo := DockerInfo{
Name: m.Container.Name,
ID: m.Container.ID,
Image: m.Container.Config.Image,
Hostname: m.Container.Config.Hostname,
}
var js []byte
var data map[string]interface{}
if err := json.Unmarshal([]byte(m.Data), &data); err != nil {
// The message is not in JSON, make a new JSON message.
msg := LogstashMessage{
Message: m.Data,
Docker: dockerInfo,
Stream: m.Source,
}
if js, err = json.Marshal(msg); err != nil {
log.Println("logstash [1]:", err)
continue
}
} else {
// The message is already in JSON, add the docker specific fields.
data["docker"] = dockerInfo
if js, err = json.Marshal(data); err != nil {
log.Println("logstash [2]:", err)
continue
}
}
if _, err := a.conn.Write(js); err != nil {
log.Println("logstash [3]:", err)
continue
}
}
}
type DockerInfo struct {
Name string `json:"name"`
ID string `json:"id"`
Image string `json:"image"`
Hostname string `json:"hostname"`
}
// LogstashMessage is a simple JSON input to Logstash.
type LogstashMessage struct {
Message string `json:"message"`
Stream string `json:"stream"`
Docker DockerInfo `json:"docker"`
}