This repository has been archived by the owner on Mar 3, 2023. It is now read-only.
forked from bshuster-repo/logrus-logstash-hook
-
Notifications
You must be signed in to change notification settings - Fork 5
/
hook.go
58 lines (52 loc) · 1.54 KB
/
hook.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
package sockrus
import (
logrus_logstash "github.com/bshuster-repo/logrus-logstash-hook"
"github.com/sirupsen/logrus"
"net"
)
// Hook represents a connection to a socket
type Hook struct {
formatter logrus.Formatter
protocol string // Protocol to the socket.
address string // Address to the socket.
addNewline bool // Toggle to send newline after every message to socket.
}
// NewHook establish a socket connection.
// Protocols allowed are: "udp", "tcp", "unix" (corresponds to SOCK_STREAM),
// "unixdomain" (corresponds to SOCK_DGRAM) or "unixpacket" (corresponds to SOCK_SEQPACKET).
//
// For TCP and UDP, address must have the form `host:port`.
//
// For Unix networks, the address must be a file system path.
func NewHook(protocol, address string, addNewline bool) (*Hook, error) {
logstashFormatter := logrus_logstash.DefaultFormatter(logrus.Fields{})
return &Hook{
protocol: protocol,
address: address,
formatter: logstashFormatter,
addNewline: addNewline,
}, nil
}
// Fire send log to the defined socket
func (h *Hook) Fire(entry *logrus.Entry) error {
var err error
dataBytes, err := h.formatter.Format(entry)
if err != nil {
return err
}
conn, err := net.Dial(h.protocol, h.address)
if err != nil {
return nil
}
defer conn.Close()
// Add new line to every message if desired.
if h.addNewline {
dataBytes = append(dataBytes, "\n"...)
}
_, _ = conn.Write(dataBytes) // #nosec
return nil
}
// Levels return an array of handled logging levels
func (h *Hook) Levels() []logrus.Level {
return logrus.AllLevels
}