-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
options.go
74 lines (61 loc) · 1.72 KB
/
options.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
package mon
import (
"reflect"
"time"
"github.com/zeromicro/go-zero/core/syncx"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/bsoncodec"
mopt "go.mongodb.org/mongo-driver/mongo/options"
)
const defaultTimeout = time.Second * 3
var (
slowThreshold = syncx.ForAtomicDuration(defaultSlowThreshold)
logMon = syncx.ForAtomicBool(true)
logSlowMon = syncx.ForAtomicBool(true)
)
type (
// Option defines the method to customize a mongo model.
Option func(opts *options)
// TypeCodec is a struct that stores specific type Encoder/Decoder.
TypeCodec struct {
ValueType reflect.Type
Encoder bsoncodec.ValueEncoder
Decoder bsoncodec.ValueDecoder
}
options = mopt.ClientOptions
)
// DisableLog disables logging of mongo commands, includes info and slow logs.
func DisableLog() {
logMon.Set(false)
logSlowMon.Set(false)
}
// DisableInfoLog disables info logging of mongo commands, but keeps slow logs.
func DisableInfoLog() {
logMon.Set(false)
}
// SetSlowThreshold sets the slow threshold.
func SetSlowThreshold(threshold time.Duration) {
slowThreshold.Set(threshold)
}
// WithTimeout set the mon client operation timeout.
func WithTimeout(timeout time.Duration) Option {
return func(opts *options) {
opts.SetTimeout(timeout)
}
}
// WithTypeCodec registers TypeCodecs to convert custom types.
func WithTypeCodec(typeCodecs ...TypeCodec) Option {
return func(opts *options) {
registry := bson.NewRegistry()
for _, v := range typeCodecs {
registry.RegisterTypeEncoder(v.ValueType, v.Encoder)
registry.RegisterTypeDecoder(v.ValueType, v.Decoder)
}
opts.SetRegistry(registry)
}
}
func defaultTimeoutOption() Option {
return func(opts *options) {
opts.SetTimeout(defaultTimeout)
}
}