Skip to content

Commit 2ce554f

Browse files
authored
Reduce computation overhead for inactive complex log messages (#5916)
If a given log level isn't active, reduce the amount of work required to call it, by fully utilizing either the delegate feature or the support for printf-style log messages.
1 parent 27eb1c8 commit 2ce554f

File tree

40 files changed

+83
-83
lines changed

40 files changed

+83
-83
lines changed

packages/datadog-instrumentations/src/cucumber.js

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -490,9 +490,7 @@ function getWrappedStart (start, frameworkVersion, isParallel = false, isCoordin
490490

491491
isSuitesSkipped = picklesToRun.length !== oldPickles.length
492492

493-
log.debug(
494-
() => `${picklesToRun.length} out of ${oldPickles.length} suites are going to run.`
495-
)
493+
log.debug('%s out of %s suites are going to run.', picklesToRun.length, oldPickles.length)
496494

497495
if (isCoordinator) {
498496
this.sourcedPickles = picklesToRun

packages/datadog-instrumentations/src/helpers/check-require-cache.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ module.exports.checkForRequiredModules = function () {
5555
if (naughties.has(pkg)) continue
5656
if (!(pkg in packages)) continue
5757

58-
warnings.push(`Warning: Package '${pkg}' was loaded before dd-trace! This may break instrumentation.`)
58+
warnings.push(() => `Warning: Package '${pkg}' was loaded before dd-trace! This may break instrumentation.`)
5959

6060
naughties.add(pkg)
6161
didWarn = true
@@ -87,7 +87,7 @@ module.exports.checkForPotentialConflicts = function () {
8787
if (naughties.has(pkg)) continue
8888
if (!potentialConflicts.has(pkg)) continue
8989

90-
warnings.push(`Warning: Package '${pkg}' may cause conflicts with dd-trace.`)
90+
warnings.push(() => `Warning: Package '${pkg}' may cause conflicts with dd-trace.`)
9191

9292
naughties.add(pkg)
9393
didWarn = true

packages/datadog-instrumentations/src/jest.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -294,15 +294,15 @@ function getWrappedEnvironment (BaseEnvironment, jestVersion) {
294294
// We'll still detect new tests, but we won't retry them.
295295
// TODO: do not bail out of retrying tests for the whole test suite
296296
if (this.getHasSnapshotTests()) {
297-
log.warn(`${retryType} is disabled for suites with snapshots`)
297+
log.warn('%s is disabled for suites with snapshots', retryType)
298298
return
299299
}
300300

301301
for (let retryIndex = 0; retryIndex < retryCount; retryIndex++) {
302302
if (this.global.test) {
303303
this.global.test(addRetryStringToTestName(testName, retryIndex), event.fn, event.timeout)
304304
} else {
305-
log.error(`${retryType} could not retry test because global.test is undefined`)
305+
log.error('%s could not retry test because global.test is undefined', retryType)
306306
}
307307
}
308308
}

packages/datadog-instrumentations/src/mocha/main.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -522,7 +522,7 @@ addHook({
522522
if (ctx) {
523523
testSuiteFinishCh.publish({ status, ...ctx.currentStore }, () => {})
524524
} else {
525-
log.warn(() => `No ctx found for suite ${suite.file}`)
525+
log.warn('No ctx found for suite', suite.file)
526526
}
527527
})
528528

packages/datadog-plugin-aws-sdk/src/services/dynamodb.js

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -119,8 +119,10 @@ class DynamoDb extends BaseAwsSdkPlugin {
119119

120120
const configStr = this._tracerConfig?.trace?.dynamoDb?.tablePrimaryKeys
121121
if (!configStr) {
122-
log.warn('Missing DD_TRACE_DYNAMODB_TABLE_PRIMARY_KEYS env variable. ' +
123-
'Please add your table\'s primary keys under this env variable.')
122+
log.warn(
123+
// eslint-disable-next-line @stylistic/max-len
124+
'Missing DD_TRACE_DYNAMODB_TABLE_PRIMARY_KEYS env variable. Please add your table\'s primary keys under this env variable.'
125+
)
124126
return
125127
}
126128

@@ -131,8 +133,11 @@ class DynamoDb extends BaseAwsSdkPlugin {
131133
if (Array.isArray(primaryKeys) && primaryKeys.length > 0 && primaryKeys.length <= 2) {
132134
config[tableName] = primaryKeys
133135
} else {
134-
log.warn(`Invalid primary key configuration for table: ${tableName}.` +
135-
'Please fix the DD_TRACE_DYNAMODB_TABLE_PRIMARY_KEYS env var.')
136+
log.warn(
137+
// eslint-disable-next-line @stylistic/max-len
138+
'Invalid primary key configuration for table: %s. Please fix the DD_TRACE_DYNAMODB_TABLE_PRIMARY_KEYS env var.',
139+
tableName
140+
)
136141
}
137142
}
138143

packages/datadog-plugin-aws-sdk/src/util.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,10 +43,10 @@ function encodeValue (valueObject) {
4343
case 'B':
4444
return Buffer.isBuffer(value) ? value : Buffer.from(value)
4545
default:
46-
log.debug(`Found unknown type while trying to create DynamoDB span pointer: ${type}`)
46+
log.debug('Found unknown type while trying to create DynamoDB span pointer:', type)
4747
}
4848
} catch (err) {
49-
log.debug(`Failed to encode value while trying to create DynamoDB span pointer: ${err.message}`)
49+
log.debug('Failed to encode value while trying to create DynamoDB span pointer:', err.message)
5050
}
5151
}
5252

packages/datadog-plugin-mocha/src/index.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -450,7 +450,7 @@ class MochaPlugin extends CiPlugin {
450450
const testSuite = span.meta[TEST_SUITE]
451451
const testSuiteSpan = this._testSuites.get(testSuite)
452452
if (!testSuiteSpan) {
453-
log.warn(`Test suite span not found for test span with test suite ${testSuite}`)
453+
log.warn('Test suite span not found for test span with test suite', testSuite)
454454
return formattedSpan
455455
}
456456
const suiteTags = getTestSuiteLevelVisibilityTags(testSuiteSpan)

packages/datadog-plugin-protobufjs/src/schema_iterator.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ class SchemaExtractor {
108108
}
109109
for (const field of schema.fieldsArray) {
110110
if (!this.extractProperty(field, schemaName, field.name, builder, depth)) {
111-
log.warn(`DSM: Unable to extract field with name: ${field.name} from Avro schema with name: ${schemaName}`)
111+
log.warn('DSM: Unable to extract field with name: %s from Avro schema with name:', field.name, schemaName)
112112
}
113113
}
114114
return true

packages/dd-trace/src/ci-visibility/dynamic-instrumentation/worker/index.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ const probeIdToBreakpointId = new Map()
3030
session.on('Debugger.paused', async ({ params: { hitBreakpoints: [hitBreakpoint], callFrames } }) => {
3131
const probe = breakpointIdToProbe.get(hitBreakpoint)
3232
if (!probe) {
33-
log.warn(`No probe found for breakpoint ${hitBreakpoint}`)
33+
log.warn('No probe found for breakpoint', hitBreakpoint)
3434
return session.post('Debugger.resume')
3535
}
3636

@@ -95,13 +95,13 @@ async function addBreakpoint (probe) {
9595

9696
const script = findScriptFromPartialPath(file)
9797
if (!script) {
98-
log.error(`No loaded script found for ${file}`)
98+
log.error('No loaded script found for', file)
9999
throw new Error(`No loaded script found for ${file}`)
100100
}
101101

102102
const { url, scriptId, sourceMapURL, source } = script
103103

104-
log.warn(`Adding breakpoint at ${url}:${line}`)
104+
log.warn('Adding breakpoint at %s:%s', url, line)
105105

106106
let lineNumber = line
107107
let columnNumber = 0

packages/dd-trace/src/ci-visibility/early-flake-detection/get-known-tests.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ function getKnownTests ({
9696
incrementCountMetric(TELEMETRY_KNOWN_TESTS_RESPONSE_TESTS, {}, numTests)
9797
distributionMetric(TELEMETRY_KNOWN_TESTS_RESPONSE_BYTES, {}, res.length)
9898

99-
log.debug(() => `Number of received known tests: ${numTests}`)
99+
log.debug('Number of received known tests:', numTests)
100100

101101
done(null, knownTests)
102102
} catch (err) {

packages/dd-trace/src/ci-visibility/exporters/agentless/coverage-writer.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ class Writer extends BaseWriter {
6868
done()
6969
return
7070
}
71-
log.debug(`Response from the intake: ${res}`)
71+
log.debug('Response from the intake:', res)
7272
done()
7373
})
7474
}

packages/dd-trace/src/ci-visibility/exporters/agentless/di-logs-writer.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ class DynamicInstrumentationLogsWriter extends BaseWriter {
4545
done()
4646
return
4747
}
48-
log.debug(`Response from the logs intake: ${res}`)
48+
log.debug('Response from the logs intake:', res)
4949
done()
5050
})
5151
}

packages/dd-trace/src/ci-visibility/exporters/agentless/writer.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ class Writer extends BaseWriter {
6969
done()
7070
return
7171
}
72-
log.debug(`Response from the intake: ${res}`)
72+
log.debug('Response from the intake:', res)
7373
done()
7474
})
7575
}

packages/dd-trace/src/ci-visibility/exporters/git/git_metadata.js

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -105,9 +105,9 @@ function getCommitsToUpload ({ url, repositoryUrl, latestCommits, isEvpProxy, ev
105105
incrementCountMetric(TELEMETRY_GIT_REQUESTS_SEARCH_COMMITS_ERRORS, { errorType: 'network' })
106106
return callback(new Error(`Can't parse commits to exclude response: ${e.message}`))
107107
}
108-
log.debug(`There are ${alreadySeenCommits.length} commits to exclude.`)
108+
log.debug('There are %s commits to exclude.', alreadySeenCommits.length)
109109
const commitsToInclude = latestCommits.filter((commit) => !alreadySeenCommits.includes(commit))
110-
log.debug(`There are ${commitsToInclude.length} commits to include.`)
110+
log.debug('There are %s commits to include.', commitsToInclude.length)
111111

112112
if (!commitsToInclude.length) {
113113
return callback(null, [])
@@ -195,11 +195,11 @@ function generateAndUploadPackFiles ({
195195
repositoryUrl,
196196
headCommit
197197
}, callback) {
198-
log.debug(`There are ${commitsToUpload.length} commits to upload`)
198+
log.debug('There are %s commits to upload', commitsToUpload.length)
199199

200200
const packFilesToUpload = generatePackFilesForCommits(commitsToUpload)
201201

202-
log.debug(`Uploading ${packFilesToUpload.length} packfiles.`)
202+
log.debug('Uploading %s packfiles.', packFilesToUpload.length)
203203

204204
if (!packFilesToUpload.length) {
205205
return callback(new Error('Failed to generate packfiles'))
@@ -253,14 +253,14 @@ function sendGitMetadata (url, { isEvpProxy, evpProxyPrefix }, configRepositoryU
253253
repositoryUrl = getRepositoryUrl()
254254
}
255255

256-
log.debug(`Uploading git history for repository ${repositoryUrl}`)
256+
log.debug('Uploading git history for repository', repositoryUrl)
257257

258258
if (!repositoryUrl) {
259259
return callback(new Error('Repository URL is empty'))
260260
}
261261

262262
let latestCommits = getLatestCommits()
263-
log.debug(`There were ${latestCommits.length} commits since last month.`)
263+
log.debug('There were %s commits since last month.', latestCommits.length)
264264

265265
const getOnFinishGetCommitsToUpload = (hasCheckedShallow) => (err, commitsToUpload) => {
266266
if (err) {

packages/dd-trace/src/ci-visibility/intelligent-test-runner/get-skippable-suites.js

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -86,10 +86,9 @@ function getSkippableSuites ({
8686
incrementCountMetric(TELEMETRY_ITR_SKIPPABLE_TESTS_ERRORS, { statusCode })
8787
done(err)
8888
} else {
89-
let skippableSuites = []
9089
try {
9190
const parsedResponse = JSON.parse(res)
92-
skippableSuites = parsedResponse
91+
const skippableSuites = parsedResponse
9392
.data
9493
.filter(({ type }) => type === testLevel)
9594
.map(({ attributes: { suite, name } }) => {
@@ -107,7 +106,7 @@ function getSkippableSuites ({
107106
skippableSuites.length
108107
)
109108
distributionMetric(TELEMETRY_ITR_SKIPPABLE_TESTS_RESPONSE_BYTES, {}, res.length)
110-
log.debug(() => `Number of received skippable ${testLevel}s: ${skippableSuites.length}`)
109+
log.debug('Number of received skippable %ss:', testLevel, skippableSuites.length)
111110
done(null, skippableSuites, correlationId)
112111
} catch (err) {
113112
done(err)

packages/dd-trace/src/ci-visibility/requests/get-library-configuration.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -122,15 +122,15 @@ function getLibraryConfiguration ({
122122
isImpactedTestsEnabled
123123
}
124124

125-
log.debug(() => `Remote settings: ${JSON.stringify(settings)}`)
125+
log.debug('Remote settings: %j', settings)
126126

127127
if (getEnvironmentVariable('DD_CIVISIBILITY_DANGEROUSLY_FORCE_COVERAGE')) {
128128
settings.isCodeCoverageEnabled = true
129-
log.debug(() => 'Dangerously set code coverage to true')
129+
log.debug('Dangerously set code coverage to true')
130130
}
131131
if (getEnvironmentVariable('DD_CIVISIBILITY_DANGEROUSLY_FORCE_TEST_SKIPPING')) {
132132
settings.isSuitesSkippingEnabled = true
133-
log.debug(() => 'Dangerously set test skipping to true')
133+
log.debug('Dangerously set test skipping to true')
134134
}
135135

136136
incrementCountMetric(TELEMETRY_GIT_REQUESTS_SETTINGS_RESPONSE, settings)

packages/dd-trace/src/config.js

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -123,12 +123,12 @@ function validateEnvVarType (envVar) {
123123
function checkIfBothOtelAndDdEnvVarSet () {
124124
for (const [otelEnvVar, ddEnvVar] of Object.entries(otelDdEnvMapping)) {
125125
if (ddEnvVar && getEnvironmentVariable(ddEnvVar) && getEnvironmentVariable(otelEnvVar)) {
126-
log.warn(`both ${ddEnvVar} and ${otelEnvVar} environment variables are set`)
126+
log.warn('both %s and %s environment variables are set', ddEnvVar, otelEnvVar)
127127
getCounter('otel.env.hiding', ddEnvVar, otelEnvVar).inc()
128128
}
129129

130130
if (getEnvironmentVariable(otelEnvVar) && !validateEnvVarType(otelEnvVar)) {
131-
log.warn(`unexpected value for ${otelEnvVar} environment variable`)
131+
log.warn('unexpected value for %s environment variable', otelEnvVar)
132132
getCounter('otel.env.invalid', ddEnvVar, otelEnvVar).inc()
133133
}
134134
}
@@ -165,9 +165,7 @@ function validateNamingVersion (versionString) {
165165
return defaultNamingVersion
166166
}
167167
if (!namingVersions.has(versionString)) {
168-
log.warn(
169-
`Unexpected input for config.spanAttributeSchema, picked default ${defaultNamingVersion}`
170-
)
168+
log.warn('Unexpected input for config.spanAttributeSchema, picked default', defaultNamingVersion)
171169
return defaultNamingVersion
172170
}
173171
return versionString
@@ -286,9 +284,8 @@ class Config {
286284
getEnvironmentVariable('DD_TRACE_PROPAGATION_STYLE_EXTRACT')
287285
)) {
288286
log.warn(
289-
'Use either the DD_TRACE_PROPAGATION_STYLE environment variable or separate ' +
290-
'DD_TRACE_PROPAGATION_STYLE_INJECT and DD_TRACE_PROPAGATION_STYLE_EXTRACT ' +
291-
'environment variables'
287+
// eslint-disable-next-line @stylistic/max-len
288+
'Use either the DD_TRACE_PROPAGATION_STYLE environment variable or separate DD_TRACE_PROPAGATION_STYLE_INJECT and DD_TRACE_PROPAGATION_STYLE_EXTRACT environment variables'
292289
)
293290
}
294291
const PROPAGATION_STYLE_INJECT = propagationStyle(

packages/dd-trace/src/datastreams/context.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ function getDataStreamsContext () {
77
}
88

99
function setDataStreamsContext (dataStreamsContext) {
10-
log.debug(() => `Setting new DSM Context: ${JSON.stringify(dataStreamsContext)}.`)
10+
log.debug('Setting new DSM Context: %j.', dataStreamsContext)
1111

1212
if (dataStreamsContext) storage('legacy').enterWith({ ...(storage('legacy').getStore()), dataStreamsContext })
1313
}

packages/dd-trace/src/datastreams/processor.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,7 @@ class DataStreamsProcessor {
204204
let closestOppositeDirectionHash = ENTRY_PARENT_HASH
205205
let closestOppositeDirectionEdgeStart = nowNs
206206
if (ctx == null) {
207-
log.debug(() => 'Setting DSM Checkpoint with empty parent context.')
207+
log.debug('Setting DSM Checkpoint with empty parent context.')
208208
} else {
209209
pathwayStartNs = ctx.pathwayStartNs
210210
edgeStartNs = ctx.edgeStartNs

packages/dd-trace/src/datastreams/writer.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ function makeRequest (data, url, cb) {
2020
url
2121
}
2222

23-
log.debug(() => `Request to the intake: ${JSON.stringify(options)}`)
23+
log.debug('Request to the intake: %j', options)
2424

2525
request(data, options, (err, res) => {
2626
cb(err, res)
@@ -39,7 +39,7 @@ class DataStreamsWriter {
3939

4040
flush (payload) {
4141
if (!request.writable) {
42-
log.debug(() => `Maximum number of active requests reached. Payload discarded: ${JSON.stringify(payload)}`)
42+
log.debug('Maximum number of active requests reached. Payload discarded: %j', payload)
4343
return
4444
}
4545
const encodedPayload = msgpack.encode(payload)
@@ -50,7 +50,7 @@ class DataStreamsWriter {
5050
return
5151
}
5252
makeRequest(compressedData, this._url, (err, res) => {
53-
log.debug(`Response from the agent: ${res}`)
53+
log.debug('Response from the agent:', res)
5454
if (err) {
5555
log.error('Error sending datastream', err)
5656
}

packages/dd-trace/src/debugger/devtools_client/index.js

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -160,10 +160,9 @@ session.on('Debugger.paused', async ({ params }) => {
160160
await session.post('Debugger.resume')
161161
const diff = process.hrtime.bigint() - start // TODO: Recored as telemetry (DEBUG-2858)
162162

163-
log.debug(
164-
'[debugger:devtools_client] Finished processing breakpoints - main thread paused for: %d ms',
163+
log.debug(() => `[debugger:devtools_client] Finished processing breakpoints - main thread paused for: ${
165164
Number(diff) / 1_000_000
166-
)
165+
} ms`)
167166

168167
const logger = {
169168
// We can safely use `location.file` from the first probe in the array, since all probes hit by `hitBreakpoints`

packages/dd-trace/src/dogstatsd.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ class DogStatsDClient {
6363
flush () {
6464
const queue = this._enqueue()
6565

66-
log.debug(`Flushing ${queue.length} metrics via ${this._httpOptions ? 'HTTP' : 'UDP'}`)
66+
log.debug('Flushing %s metrics via', queue.length, this._httpOptions ? 'HTTP' : 'UDP')
6767

6868
if (this._queue.length === 0) return
6969

@@ -108,7 +108,7 @@ class DogStatsDClient {
108108
const socket = family === 6 ? this._udp6 : this._udp4
109109

110110
queue.forEach((buffer) => {
111-
log.debug(`Sending to DogStatsD: ${buffer}`)
111+
log.debug('Sending to DogStatsD:', buffer)
112112
socket.send(buffer, 0, buffer.length, this._port, address)
113113
})
114114
}

packages/dd-trace/src/exporters/agent/writer.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ function makeRequest (version, data, count, url, headers, lookup, needsStartupLo
9292
setHeader(options.headers, 'Datadog-Meta-Lang-Version', process.version)
9393
setHeader(options.headers, 'Datadog-Meta-Lang-Interpreter', process.jsEngine || 'v8')
9494

95-
log.debug(() => `Request to the agent: ${JSON.stringify(options)}`)
95+
log.debug('Request to the agent: %j', options)
9696

9797
request(data, options, (err, res, status) => {
9898
if (needsStartupLog) {

packages/dd-trace/src/exporters/log/index.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ const MAX_SIZE = 64 * 1024 // 64kb
99

1010
class LogExporter {
1111
export (spans) {
12-
log.debug(() => `Adding trace to queue: ${JSON.stringify(spans)}`)
12+
log.debug('Adding trace to queue: %j', spans)
1313

1414
let size = TRACE_FORMAT_OVERHEAD
1515
let queue = []

0 commit comments

Comments
 (0)