@@ -30,7 +30,7 @@ type SplunkHook struct {
30
30
FlushFreq time.Duration
31
31
MaxFlushSize int
32
32
33
- msg chan * SplunkLog
33
+ msg chan * logrus. Entry
34
34
}
35
35
36
36
func NewSplunkHook (client * http.Client , endpoint string , token string , flushFreq time.Duration , maxFlushSize int ) logrus.Hook {
@@ -46,18 +46,18 @@ func NewSplunkHook(client *http.Client, endpoint string, token string, flushFreq
46
46
if hook .FlushFreq == 0 {
47
47
hook .FlushFreq = 1 * time .Second
48
48
}
49
- hook .msg = make (chan * SplunkLog , hook .MaxFlushSize )
49
+ hook .msg = make (chan * logrus. Entry , hook .MaxFlushSize )
50
50
go hook .manageBuffer ()
51
51
return hook
52
52
}
53
53
54
54
func (s * SplunkHook ) manageBuffer () {
55
55
ticker := time .NewTicker (s .FlushFreq )
56
56
57
- buf := make ([]* SplunkLog , 0 )
57
+ buf := make ([]* logrus. Entry , 0 )
58
58
flush := func () {
59
59
go s .doSend (buf )
60
- buf = make ([]* SplunkLog , 0 )
60
+ buf = make ([]* logrus. Entry , 0 )
61
61
}
62
62
for {
63
63
select {
@@ -76,17 +76,30 @@ func (s *SplunkHook) manageBuffer() {
76
76
77
77
// doSend is synchronous with the actual HTTP send
78
78
// errors are all ignored.
79
- func (s * SplunkHook ) doSend (logs []* SplunkLog ) {
79
+ func (s * SplunkHook ) doSend (logs []* logrus.Entry ) {
80
+ // buffer and its underlying contents
80
81
_b := []byte {}
81
82
outputBuf := bytes .NewBuffer (_b )
83
+
84
+ // a json encoder to serialize the splunk log into the buffer
82
85
encoder := json .NewEncoder (outputBuf )
86
+
87
+ // for each log built up request:
88
+ //encode the log content into bytes, wrap it in its metadata, and JSON encode into the buffer
83
89
for i := range logs {
84
- _ = encoder .Encode (logs [i ])
90
+ b , _ := formatter .Format (logs [i ])
91
+ _ = encoder .Encode (& SplunkLog {
92
+ Time : logs [i ].Time .UnixNano (),
93
+ Host : host ,
94
+ Event : b ,
95
+ })
85
96
}
86
97
98
+ // build the HTTP request to send it to splunk
87
99
req , _ := http .NewRequest (http .MethodPost , s .Endpoint , outputBuf )
88
-
89
100
req .Header .Set ("Authorization" , fmt .Sprintf ("Splunk %s" , s .Token ))
101
+
102
+ // and execute it
90
103
res , err := s .Client .Do (req )
91
104
if err != nil {
92
105
fmt .Println (err )
@@ -104,15 +117,8 @@ func (s *SplunkHook) Levels() []logrus.Level {
104
117
}
105
118
106
119
func (s * SplunkHook ) Fire (e * logrus.Entry ) error {
107
- b , err := formatter .Format (e )
108
-
109
- s .msg <- & SplunkLog {
110
- Time : e .Time .UnixNano (),
111
- Host : host ,
112
- Event : b ,
113
- }
114
-
115
- return err
120
+ s .msg <- e
121
+ return nil
116
122
}
117
123
118
124
type SplunkLog struct {
0 commit comments