Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ddtrace/tracer: Remove log.Debug from hot path (-2 allocs; -5% CPU) #1186

Merged
merged 4 commits into from Mar 8, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 5 additions & 1 deletion ddtrace/tracer/tracer.go
Expand Up @@ -417,7 +417,11 @@ func (t *tracer) StartSpan(operationName string, options ...ddtrace.StartSpanOpt
span.Service = newSvc
}
}
log.Debug("Started Span: %v, Operation: %s, Resource: %s, Tags: %v, %v", span, span.Name, span.Resource, span.Meta, span.Metrics)
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
9 changes: 9 additions & 0 deletions internal/log/log.go
Expand Up @@ -56,6 +56,15 @@ func SetLevel(lvl Level) {
level = lvl
}

// 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()
return lvl == LevelDebug
}

// Debug prints the given message if the level is LevelDebug.
func Debug(fmt string, a ...interface{}) {
mu.RLock()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NIT: Remove code duplication by calling DebugEnabled() here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oops excellent suggestion; fixed

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