Skip to content

Commit

Permalink
ddtrace/tracer: Remove log.Debug from hot path (-2 allocs; -5% CPU) (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
evanj committed Mar 8, 2022
1 parent 7c11ba8 commit 5b114be
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 4 deletions.
11 changes: 10 additions & 1 deletion ddtrace/tracer/tracer.go
Expand Up @@ -434,7 +434,16 @@ func (t *tracer) StartSpan(operationName string, options ...ddtrace.StartSpanOpt
if t.config.profilerHotspots || t.config.profilerEndpoints {
t.applyPPROFLabels(pprofContext, span)
}
log.Debug("Started Span: %v, Operation: %s, Resource: %s, Tags: %v, %v", span, span.Name, span.Resource, span.Meta, span.Metrics)
if t.config.serviceMappings != nil {
if newSvc, ok := t.config.serviceMappings[span.Service]; ok {
span.Service = newSvc
}
}
if log.DebugEnabled() {
// avoid allocating the ...interface{} argument if debug logging is disabled
log.Debug("Started Span: %v, Operation: %s, Resource: %s, Tags: %v, %v",
span, span.Name, span.Resource, span.Meta, span.Metrics)
}
return span
}

Expand Down
12 changes: 9 additions & 3 deletions internal/log/log.go
Expand Up @@ -56,12 +56,18 @@ func SetLevel(lvl Level) {
level = lvl
}

// Debug prints the given message if the level is LevelDebug.
func Debug(fmt string, a ...interface{}) {
// DebugEnabled returns true if debug log messages are enabled. This can be used in extremely
// hot code paths to avoid allocating the ...interface{} argument.
func DebugEnabled() bool {
mu.RLock()
lvl := level
mu.RUnlock()
if lvl != LevelDebug {
return lvl == LevelDebug
}

// Debug prints the given message if the level is LevelDebug.
func Debug(fmt string, a ...interface{}) {
if !DebugEnabled() {
return
}
printMsg("DEBUG", fmt, a...)
Expand Down
2 changes: 2 additions & 0 deletions internal/log/log_test.go
Expand Up @@ -60,13 +60,15 @@ func TestLog(t *testing.T) {
tp.Reset()
defer func(old Level) { level = old }(level)
SetLevel(LevelDebug)
assert.True(t, DebugEnabled())

Debug("message %d", 3)
assert.Equal(t, msg("DEBUG", "message 3"), tp.Lines()[0])
})

t.Run("off", func(t *testing.T) {
tp.Reset()
assert.False(t, DebugEnabled())
Debug("message %d", 2)
assert.Len(t, tp.Lines(), 0)
})
Expand Down

0 comments on commit 5b114be

Please sign in to comment.