Skip to content

Commit 84eb6cf

Browse files
minor logging refactor: work done in bulk during HTTP request, and original typing carried closer to request
1 parent be327c8 commit 84eb6cf

File tree

1 file changed

+22
-16
lines changed

1 file changed

+22
-16
lines changed

logging/log.go

+22-16
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ type SplunkHook struct {
3030
FlushFreq time.Duration
3131
MaxFlushSize int
3232

33-
msg chan *SplunkLog
33+
msg chan *logrus.Entry
3434
}
3535

3636
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
4646
if hook.FlushFreq == 0 {
4747
hook.FlushFreq = 1 * time.Second
4848
}
49-
hook.msg = make(chan *SplunkLog, hook.MaxFlushSize)
49+
hook.msg = make(chan *logrus.Entry, hook.MaxFlushSize)
5050
go hook.manageBuffer()
5151
return hook
5252
}
5353

5454
func (s *SplunkHook) manageBuffer() {
5555
ticker := time.NewTicker(s.FlushFreq)
5656

57-
buf := make([]*SplunkLog, 0)
57+
buf := make([]*logrus.Entry, 0)
5858
flush := func() {
5959
go s.doSend(buf)
60-
buf = make([]*SplunkLog, 0)
60+
buf = make([]*logrus.Entry, 0)
6161
}
6262
for {
6363
select {
@@ -76,17 +76,30 @@ func (s *SplunkHook) manageBuffer() {
7676

7777
// doSend is synchronous with the actual HTTP send
7878
// 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
8081
_b := []byte{}
8182
outputBuf := bytes.NewBuffer(_b)
83+
84+
// a json encoder to serialize the splunk log into the buffer
8285
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
8389
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+
})
8596
}
8697

98+
// build the HTTP request to send it to splunk
8799
req, _ := http.NewRequest(http.MethodPost, s.Endpoint, outputBuf)
88-
89100
req.Header.Set("Authorization", fmt.Sprintf("Splunk %s", s.Token))
101+
102+
// and execute it
90103
res, err := s.Client.Do(req)
91104
if err != nil {
92105
fmt.Println(err)
@@ -104,15 +117,8 @@ func (s *SplunkHook) Levels() []logrus.Level {
104117
}
105118

106119
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
116122
}
117123

118124
type SplunkLog struct {

0 commit comments

Comments
 (0)