-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcls_async.go
85 lines (71 loc) · 1.58 KB
/
cls_async.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
package logruscls
import (
"log"
"time"
"github.com/chuangbo/logruscls/pb"
)
// CLSAsyncClient to send logs to cls in batch on the background.
type CLSAsyncClient struct {
// max number of one batch upload
batch int
// max delay
delay time.Duration
cls *CLSClient
logs chan *pb.Log
}
// NewCLSAsyncClient creates a async version of CLSClient
func NewCLSAsyncClient(region, secretID, secretKey, topicID string, batch int, delay time.Duration) (*CLSAsyncClient, error) {
client, err := NewCLSClient(region, secretID, secretKey, topicID)
if err != nil {
return nil, err
}
asyncClient := &CLSAsyncClient{
batch: batch,
delay: delay,
// double buffer
logs: make(chan *pb.Log, batch*2),
cls: client,
}
// upload in batch in a goroutine
go asyncClient.startSender()
return asyncClient, nil
}
// Log put one log to the logs queue
func (c *CLSAsyncClient) Log(log *pb.Log) error {
c.logs <- log
return nil
}
// startSender
func (c *CLSAsyncClient) startSender() {
for {
logs := []*pb.Log{}
t := time.NewTimer(c.delay)
receiveLoop:
// receive either maximum number of `batch` logs or wait for max `delay` time
for {
select {
case <-t.C:
if len(logs) > 0 {
break receiveLoop
}
t.Reset(c.delay)
case l := <-c.logs:
logs = append(logs, l)
if len(logs) >= c.batch {
break receiveLoop
}
}
}
logGroupList := &pb.LogGroupList{
LogGroupList: []*pb.LogGroup{
{
Logs: logs,
},
},
}
err := c.cls.UploadStructuredLog(logGroupList)
if err != nil {
log.Printf("could not upload to cls: %v", err)
}
}
}