-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpubzap.go
101 lines (85 loc) · 2.26 KB
/
pubzap.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
package pubzap
import (
"context"
"fmt"
"io"
"log"
"net/url"
"path"
"time"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"gocloud.dev/pubsub"
_ "gocloud.dev/pubsub/gcppubsub"
_ "gocloud.dev/pubsub/mempubsub"
)
var defaultPublishTimeout = 1 * time.Second
var schemas = []string{"mem", "gcppubsub"}
// we need to tell zap to recognize pubsub urls.
func init() {
for _, schema := range schemas {
if err := registerSink(schema); err != nil {
panic(err)
}
}
}
// registerSink
// url format:
// host and path is a topic name
// query:
// - publishTimeout=X where X A duration string is a possibly signed
// sequence of decimal numbers, each with optional fraction and a unit suffix,
// such as "300ms", "-1.5h" or "2h45m".
// Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
func registerSink(protocol string) error {
return zap.RegisterSink(protocol, func(u *url.URL) (zap.Sink, error) {
topicName := path.Join(u.Host, u.Path)
publishTimeout := defaultPublishTimeout
publishTimeoutRaw := u.Query().Get("publishTimeout")
if publishTimeoutRaw != "" {
var err error
publishTimeout, err = time.ParseDuration(publishTimeoutRaw)
if err != nil {
return nil, err
}
}
ctx := context.Background()
topic, err := pubsub.OpenTopic(ctx, fmt.Sprintf("%s://%s", protocol, topicName))
if err != nil {
return nil, err
}
return &pubsubSink{topic: topic, publishTimeout: publishTimeout}, nil
})
}
// pubsubSink is struct that satisfies zap.Sink
type pubsubSink struct {
topic *pubsub.Topic
publishTimeout time.Duration
zapcore.WriteSyncer
io.Closer
}
// Close implement io.Closer.
func (zpb *pubsubSink) Close() error {
return zpb.topic.Shutdown(context.Background())
}
// Write implement zap.Sink func Write
func (zpb *pubsubSink) Write(b []byte) (int, error) {
go func() {
ctx, cancel := context.WithTimeout(context.Background(), zpb.publishTimeout)
defer cancel()
err := zpb.topic.Send(ctx, &pubsub.Message{
Body: b,
Metadata: map[string]string{
"pubsubbeat.batch_ndjson": "true",
},
})
if err != nil {
log.Printf("failed to send a pubsub message: %s", err)
}
}()
return len(b), nil
}
// Sync implement zap.Sink func Sync. In fact, we do nothing here.
func (zpb *pubsubSink) Sync() error {
return nil
}