github.com/matrixorigin/matrixone@v1.2.0/pkg/util/metric/stats/registry.go (about) 1 // Copyright 2023 Matrix Origin 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package stats 16 17 import ( 18 "go.uber.org/zap" 19 "sync" 20 ) 21 22 // Registry holds mapping between FamilyName and Family 23 type Registry struct { 24 sync.RWMutex 25 families map[string]*Family 26 } 27 28 func NewRegistry() *Registry { 29 return &Registry{ 30 families: make(map[string]*Family), 31 } 32 } 33 34 func (r *Registry) Register(familyName string, opts ...Options) { 35 r.Lock() 36 defer r.Unlock() 37 38 if _, exists := r.families[familyName]; exists { 39 panic("Duplicate Family Name " + familyName) 40 } 41 42 initOpts := defaultOptions() 43 for _, optFunc := range opts { 44 optFunc(&initOpts) 45 } 46 47 r.families[familyName] = &Family{ 48 logExporter: initOpts.logExporter, 49 } 50 } 51 52 // Unregister deletes the item with familyName from map. 53 func (r *Registry) Unregister(familyName string) { 54 r.Lock() 55 defer r.Unlock() 56 57 delete(r.families, familyName) 58 } 59 60 // ExportLog returns the snapshot of all the Family in the registry 61 func (r *Registry) ExportLog() map[string][]zap.Field { 62 r.RLock() 63 defer r.RUnlock() 64 65 families := make(map[string][]zap.Field) 66 for familyName, family := range r.families { 67 families[familyName] = family.logExporter.Export() 68 } 69 return families 70 } 71 72 // WithLogExporter registers Family with the LogExporter 73 func WithLogExporter(logExporter LogExporter) Options { 74 return func(o *options) { 75 o.logExporter = logExporter 76 } 77 } 78 79 type Options func(*options) 80 81 type options struct { 82 logExporter LogExporter 83 } 84 85 func defaultOptions() options { 86 return options{} 87 } 88 89 // DefaultRegistry will be used to register all the MO Dev Stats. 90 var DefaultRegistry = NewRegistry() 91 92 // Register registers stats family to default stats registry 93 // familyName is a unique family name for the stats 94 // opts can contain logExporter etc. for the stats. 95 // Usage: stats.Register("FamilyName", stats.WithLogExporter(customStatsLogExporter)) 96 func Register(familyName string, opts ...Options) { 97 DefaultRegistry.Register(familyName, opts...) 98 } 99 100 // Unregister unregisters the family from DefaultRegistry. 101 func Unregister(familyName string) { 102 DefaultRegistry.Unregister(familyName) 103 }