github.com/blend/go-sdk@v1.20220411.3/stats/error_listeners.go (about) 1 /* 2 3 Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package stats 9 10 import ( 11 "context" 12 "fmt" 13 14 "github.com/blend/go-sdk/ex" 15 "github.com/blend/go-sdk/logger" 16 ) 17 18 // AddErrorListeners adds error listeners. 19 func AddErrorListeners(log logger.Listenable, stats Collector, opts ...AddListenerOption) { 20 if log == nil || stats == nil { 21 return 22 } 23 24 options := NewAddListenerOptions(opts...) 25 26 listener := logger.NewErrorEventListener(func(ctx context.Context, ee logger.ErrorEvent) { 27 tags := []string{ 28 Tag(TagSeverity, string(ee.GetFlag())), 29 } 30 tags = append(tags, options.GetLoggerLabelsAsTags(ctx)...) 31 _ = stats.Increment(MetricNameError, 32 tags..., 33 ) 34 }) 35 log.Listen(logger.Warning, ListenerNameStats, listener) 36 log.Listen(logger.Error, ListenerNameStats, listener) 37 log.Listen(logger.Fatal, ListenerNameStats, listener) 38 } 39 40 // AddErrorListenersByClass adds error listeners that add an exception class tag. 41 // 42 // NOTE: this will create many tag values if you do not use exceptions correctly, 43 // that is, if you put variable data in the exception class. 44 // If there is any doubt which of these to use (AddErrorListeners or AddErrorListenersByClass) 45 // use the version that does not add the class information (AddErrorListeners). 46 func AddErrorListenersByClass(log logger.Listenable, stats Collector, opts ...AddListenerOption) { 47 if log == nil || stats == nil { 48 return 49 } 50 51 options := NewAddListenerOptions(opts...) 52 53 listener := logger.NewErrorEventListener(func(ctx context.Context, ee logger.ErrorEvent) { 54 tags := []string{ 55 Tag(TagSeverity, string(ee.GetFlag())), 56 Tag(TagClass, fmt.Sprintf("%v", ex.ErrClass(ee.Err))), 57 } 58 tags = append(tags, options.GetLoggerLabelsAsTags(ctx)...) 59 _ = stats.Increment(MetricNameError, 60 tags..., 61 ) 62 }) 63 log.Listen(logger.Warning, ListenerNameStats, listener) 64 log.Listen(logger.Error, ListenerNameStats, listener) 65 log.Listen(logger.Fatal, ListenerNameStats, listener) 66 }