-
Notifications
You must be signed in to change notification settings - Fork 61
/
gelf.go
110 lines (95 loc) · 2.52 KB
/
gelf.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
package gelf
import (
"encoding/json"
"errors"
"log"
"os"
"strings"
"time"
"github.com/Graylog2/go-gelf/gelf"
"github.com/gliderlabs/logspout/router"
)
var hostname string
func init() {
hostname, _ = os.Hostname()
router.AdapterFactories.Register(NewGelfAdapter, "gelf")
}
// GelfAdapter is an adapter that streams UDP JSON to Graylog
type GelfAdapter struct {
writer *gelf.Writer
route *router.Route
}
// NewGelfAdapter creates a GelfAdapter with UDP as the default transport.
func NewGelfAdapter(route *router.Route) (router.LogAdapter, error) {
_, found := router.AdapterTransports.Lookup(route.AdapterTransport("udp"))
if !found {
return nil, errors.New("unable to find adapter: " + route.Adapter)
}
gelfWriter, err := gelf.NewWriter(route.Address)
if err != nil {
return nil, err
}
return &GelfAdapter{
route: route,
writer: gelfWriter,
}, nil
}
// Stream implements the router.LogAdapter interface.
func (a *GelfAdapter) Stream(logstream chan *router.Message) {
for message := range logstream {
m := &GelfMessage{message}
level := gelf.LOG_INFO
if m.Source == "stderr" {
level = gelf.LOG_ERR
}
extra, err := m.getExtraFields()
if err != nil {
log.Println("Graylog:", err)
continue
}
msg := gelf.Message{
Version: "1.1",
Host: hostname,
Short: m.Message.Data,
TimeUnix: float64(m.Message.Time.UnixNano()/int64(time.Millisecond)) / 1000.0,
Level: level,
RawExtra: extra,
}
// ContainerId: m.Container.ID,
// ContainerImage: m.Container.Config.Image,
// ContainerName: m.Container.Name,
// }
// here be message write.
if err := a.writer.WriteMessage(&msg); err != nil {
log.Println("Graylog:", err)
continue
}
}
}
type GelfMessage struct {
*router.Message
}
func (m GelfMessage) getExtraFields() (json.RawMessage, error) {
extra := map[string]interface{}{
"_container_id": m.Container.ID,
"_container_name": m.Container.Name[1:], // might be better to use strings.TrimLeft() to remove the first /
"_image_id": m.Container.Image,
"_image_name": m.Container.Config.Image,
"_command": strings.Join(m.Container.Config.Cmd[:], " "),
"_created": m.Container.Created,
}
for name, label := range m.Container.Config.Labels {
if len(name) > 5 && strings.ToLower(name[0:5]) == "gelf_" {
extra[name[4:]] = label
}
}
swarmnode := m.Container.Node
if swarmnode != nil {
extra["_swarm_node"] = swarmnode.Name
}
rawExtra, err := json.Marshal(extra)
if err != nil {
return nil, err
}
return rawExtra, nil
}