@@ -20,6 +20,7 @@ import (
2020
2121 "github.com/alibaba/sentinel-golang/core/base"
2222 sbase "github.com/alibaba/sentinel-golang/core/stat/base"
23+ metric_exporter "github.com/alibaba/sentinel-golang/exporter/metric"
2324 "github.com/alibaba/sentinel-golang/logging"
2425 "github.com/alibaba/sentinel-golang/util"
2526 "github.com/pkg/errors"
@@ -47,6 +48,17 @@ const (
4748 Open
4849)
4950
51+ var (
52+ stateChangedCounter = metric_exporter .NewCounter (
53+ "circuit_breaker_state_changed_total" ,
54+ "Circuit breaker total state change count" ,
55+ []string {"resource" , "from_state" , "to_state" })
56+ )
57+
58+ func init () {
59+ metric_exporter .Register (stateChangedCounter )
60+ }
61+
5062func newState () * State {
5163 var state State
5264 state = Closed
@@ -152,6 +164,8 @@ func (b *circuitBreakerBase) fromClosedToOpen(snapshot interface{}) bool {
152164 for _ , listener := range stateChangeListeners {
153165 listener .OnTransformToOpen (Closed , * b .rule , snapshot )
154166 }
167+
168+ stateChangedCounter .Add (float64 (1 ), b .BoundRule ().Resource , "Closed" , "Open" )
155169 return true
156170 }
157171 return false
@@ -181,6 +195,8 @@ func (b *circuitBreakerBase) fromOpenToHalfOpen(ctx *base.EntryContext) bool {
181195 return nil
182196 })
183197 }
198+
199+ stateChangedCounter .Add (float64 (1 ), b .BoundRule ().Resource , "Open" , "HalfOpen" )
184200 return true
185201 }
186202 return false
@@ -194,6 +210,8 @@ func (b *circuitBreakerBase) fromHalfOpenToOpen(snapshot interface{}) bool {
194210 for _ , listener := range stateChangeListeners {
195211 listener .OnTransformToOpen (HalfOpen , * b .rule , snapshot )
196212 }
213+
214+ stateChangedCounter .Add (float64 (1 ), b .BoundRule ().Resource , "HalfOpen" , "Open" )
197215 return true
198216 }
199217 return false
@@ -206,6 +224,8 @@ func (b *circuitBreakerBase) fromHalfOpenToClosed() bool {
206224 for _ , listener := range stateChangeListeners {
207225 listener .OnTransformToClosed (HalfOpen , * b .rule )
208226 }
227+
228+ stateChangedCounter .Add (float64 (1 ), b .BoundRule ().Resource , "HalfOpen" , "Closed" )
209229 return true
210230 }
211231 return false
0 commit comments