Skip to content

Commit

Permalink
feat: allow ignore by condition (#32)
Browse files Browse the repository at this point in the history
Signed-off-by: rogerogers <rogers@rogerogers.com>
  • Loading branch information
rogerogers authored Dec 30, 2023
1 parent f459e1d commit 7d3e01e
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
4 changes: 4 additions & 0 deletions tracing/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,10 @@ func ClientMiddleware(opts ...Option) client.Middleware {

func ServerMiddleware(cfg *Config) app.HandlerFunc {
return func(ctx context.Context, c *app.RequestContext) {
if cfg.shouldIgnore(ctx, c) {
c.Next(ctx)
return
}
// get tracer carrier
tc := internal.TraceCarrierFromContext(ctx)
if tc == nil {
Expand Down
13 changes: 13 additions & 0 deletions tracing/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ func (fn option) apply(cfg *Config) {
fn(cfg)
}

type ConditionFunc func(ctx context.Context, c *app.RequestContext) bool

type Config struct {
tracer trace.Tracer
meter metric.Meter
Expand All @@ -54,6 +56,7 @@ type Config struct {
recordSourceOperation bool

customResponseHandler app.HandlerFunc
shouldIgnore ConditionFunc
}

func newConfig(opts []Option) *Config {
Expand Down Expand Up @@ -95,6 +98,9 @@ func defaultConfig() *Config {
}
return route
},
shouldIgnore: func(ctx context.Context, c *app.RequestContext) bool {
return false
},
}
}

Expand Down Expand Up @@ -132,3 +138,10 @@ func WithServerHttpRouteFormatter(serverHttpRouteFormatter func(c *app.RequestCo
cfg.serverHttpRouteFormatter = serverHttpRouteFormatter
})
}

// WithShouldIgnore allows you to define the condition for enabling distributed tracing
func WithShouldIgnore(condition ConditionFunc) Option {
return option(func(cfg *Config) {
cfg.shouldIgnore = condition
})
}
8 changes: 7 additions & 1 deletion tracing/tracer_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,14 +73,20 @@ func (s *serverTracer) createMeasures() {
s.histogramRecorder[ServerLatency] = serverLatencyMeasure
}

func (s *serverTracer) Start(ctx context.Context, _ *app.RequestContext) context.Context {
func (s *serverTracer) Start(ctx context.Context, c *app.RequestContext) context.Context {
if s.config.shouldIgnore(ctx, c) {
return ctx
}
tc := &internal.TraceCarrier{}
tc.SetTracer(s.config.tracer)

return internal.WithTraceCarrier(ctx, tc)
}

func (s *serverTracer) Finish(ctx context.Context, c *app.RequestContext) {
if s.config.shouldIgnore(ctx, c) {
return
}
// trace carrier from context
tc := internal.TraceCarrierFromContext(ctx)
if tc == nil {
Expand Down

0 comments on commit 7d3e01e

Please sign in to comment.