Skip to content

Commit 99360ba

Browse files
authored
ref(node-core|node): Use debug instead of logger (#17025)
resolves #16946 resolves #16947
1 parent 713ef4b commit 99360ba

28 files changed

+160
-168
lines changed

packages/node-core/src/integrations/anr/index.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,14 @@ import { types } from 'node:util';
22
import { Worker } from 'node:worker_threads';
33
import type { Contexts, Event, EventHint, Integration, IntegrationFn, ScopeData } from '@sentry/core';
44
import {
5+
debug,
56
defineIntegration,
67
getClient,
78
getCurrentScope,
89
getFilenameToDebugIdMap,
910
getGlobalScope,
1011
getIsolationScope,
1112
GLOBAL_OBJ,
12-
logger,
1313
mergeScopeData,
1414
} from '@sentry/core';
1515
import { NODE_VERSION } from '../../nodeVersion';
@@ -26,7 +26,7 @@ const DEFAULT_INTERVAL = 50;
2626
const DEFAULT_HANG_THRESHOLD = 5000;
2727

2828
function log(message: string, ...args: unknown[]): void {
29-
logger.log(`[ANR] ${message}`, ...args);
29+
debug.log(`[ANR] ${message}`, ...args);
3030
}
3131

3232
function globalWithScopeFetchFn(): typeof GLOBAL_OBJ & { __SENTRY_GET_SCOPES__?: () => ScopeData } {
@@ -104,7 +104,7 @@ const _anrIntegration = ((options: Partial<AnrIntegrationOptions> = {}) => {
104104
client = initClient;
105105

106106
if (options.captureStackTrace && (await isDebuggerEnabled())) {
107-
logger.warn('ANR captureStackTrace has been disabled because the debugger was already enabled');
107+
debug.warn('ANR captureStackTrace has been disabled because the debugger was already enabled');
108108
options.captureStackTrace = false;
109109
}
110110

@@ -188,7 +188,7 @@ async function _startWorker(
188188
}
189189

190190
const options: WorkerStartData = {
191-
debug: logger.isEnabled(),
191+
debug: debug.isEnabled(),
192192
dsn,
193193
tunnel: initOptions.tunnel,
194194
environment: initOptions.environment || 'production',

packages/node-core/src/integrations/contextlines.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { createReadStream } from 'node:fs';
22
import { createInterface } from 'node:readline';
33
import type { Event, IntegrationFn, StackFrame } from '@sentry/core';
4-
import { defineIntegration, logger, LRUMap, snipLine } from '@sentry/core';
4+
import { debug, defineIntegration, LRUMap, snipLine } from '@sentry/core';
55
import { DEBUG_BUILD } from '../debug-build';
66

77
const LRU_FILE_CONTENTS_CACHE = new LRUMap<string, Record<number, string>>(10);
@@ -167,7 +167,7 @@ function getContextLinesFromFile(path: string, ranges: ReadlineRange[], output:
167167
function onStreamError(e: Error): void {
168168
// Mark file path as failed to read and prevent multiple read attempts.
169169
LRU_FILE_CONTENTS_FS_READ_FAILED.set(path, 1);
170-
DEBUG_BUILD && logger.error(`Failed to read file: ${path}. Error: ${e}`);
170+
DEBUG_BUILD && debug.error(`Failed to read file: ${path}. Error: ${e}`);
171171
lineReaded.close();
172172
lineReaded.removeAllListeners();
173173
destroyStreamAndResolve();
@@ -281,7 +281,7 @@ async function addSourceContext(event: Event, contextLines: number): Promise<Eve
281281

282282
// The promise rejections are caught in order to prevent them from short circuiting Promise.all
283283
await Promise.all(readlinePromises).catch(() => {
284-
DEBUG_BUILD && logger.log('Failed to read one or more source files and resolve context lines');
284+
DEBUG_BUILD && debug.log('Failed to read one or more source files and resolve context lines');
285285
});
286286

287287
// Perform the same loop as above, but this time we can assume all files are in the cache
@@ -339,7 +339,7 @@ export function addContextToFrame(
339339
// When there is no line number in the frame, attaching context is nonsensical and will even break grouping.
340340
// We already check for lineno before calling this, but since StackFrame lineno ism optional, we check it again.
341341
if (frame.lineno === undefined || contents === undefined) {
342-
DEBUG_BUILD && logger.error('Cannot resolve context for frame with no lineno or file contents');
342+
DEBUG_BUILD && debug.error('Cannot resolve context for frame with no lineno or file contents');
343343
return;
344344
}
345345

@@ -350,7 +350,7 @@ export function addContextToFrame(
350350
const line = contents[i];
351351
if (line === undefined) {
352352
clearLineContext(frame);
353-
DEBUG_BUILD && logger.error(`Could not find line ${i} in file ${frame.filename}`);
353+
DEBUG_BUILD && debug.error(`Could not find line ${i} in file ${frame.filename}`);
354354
return;
355355
}
356356

@@ -361,7 +361,7 @@ export function addContextToFrame(
361361
// without adding any linecontext.
362362
if (contents[lineno] === undefined) {
363363
clearLineContext(frame);
364-
DEBUG_BUILD && logger.error(`Could not find line ${lineno} in file ${frame.filename}`);
364+
DEBUG_BUILD && debug.error(`Could not find line ${lineno} in file ${frame.filename}`);
365365
return;
366366
}
367367

packages/node-core/src/integrations/http/SentryHttpInstrumentation.ts

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import type { AggregationCounts, Client, SanitizedRequestData, Scope } from '@se
1212
import {
1313
addBreadcrumb,
1414
addNonEnumerableProperty,
15+
debug,
1516
generateSpanId,
1617
getBreadcrumbLogLevelFromHttpStatusCode,
1718
getClient,
@@ -21,7 +22,6 @@ import {
2122
getTraceData,
2223
httpRequestToRequestData,
2324
isError,
24-
logger,
2525
LRUMap,
2626
parseUrl,
2727
SDK_VERSION,
@@ -219,7 +219,7 @@ export class SentryHttpInstrumentation extends InstrumentationBase<SentryHttpIns
219219
* It has access to the final request and response objects.
220220
*/
221221
private _onOutgoingRequestFinish(request: http.ClientRequest, response?: http.IncomingMessage): void {
222-
DEBUG_BUILD && logger.log(INSTRUMENTATION_NAME, 'Handling finished outgoing request');
222+
DEBUG_BUILD && debug.log(INSTRUMENTATION_NAME, 'Handling finished outgoing request');
223223

224224
const _breadcrumbs = this.getConfig().breadcrumbs;
225225
const breadCrumbsEnabled = typeof _breadcrumbs === 'undefined' ? true : _breadcrumbs;
@@ -266,10 +266,10 @@ export class SentryHttpInstrumentation extends InstrumentationBase<SentryHttpIns
266266
if (sentryTrace && !request.getHeader('sentry-trace')) {
267267
try {
268268
request.setHeader('sentry-trace', sentryTrace);
269-
DEBUG_BUILD && logger.log(INSTRUMENTATION_NAME, 'Added sentry-trace header to outgoing request');
269+
DEBUG_BUILD && debug.log(INSTRUMENTATION_NAME, 'Added sentry-trace header to outgoing request');
270270
} catch (error) {
271271
DEBUG_BUILD &&
272-
logger.error(
272+
debug.error(
273273
INSTRUMENTATION_NAME,
274274
'Failed to add sentry-trace header to outgoing request:',
275275
isError(error) ? error.message : 'Unknown error',
@@ -283,10 +283,10 @@ export class SentryHttpInstrumentation extends InstrumentationBase<SentryHttpIns
283283
if (newBaggage) {
284284
try {
285285
request.setHeader('baggage', newBaggage);
286-
DEBUG_BUILD && logger.log(INSTRUMENTATION_NAME, 'Added baggage header to outgoing request');
286+
DEBUG_BUILD && debug.log(INSTRUMENTATION_NAME, 'Added baggage header to outgoing request');
287287
} catch (error) {
288288
DEBUG_BUILD &&
289-
logger.error(
289+
debug.error(
290290
INSTRUMENTATION_NAME,
291291
'Failed to add baggage header to outgoing request:',
292292
isError(error) ? error.message : 'Unknown error',
@@ -309,7 +309,7 @@ export class SentryHttpInstrumentation extends InstrumentationBase<SentryHttpIns
309309
return;
310310
}
311311

312-
DEBUG_BUILD && logger.log(INSTRUMENTATION_NAME, 'Patching server.emit');
312+
DEBUG_BUILD && debug.log(INSTRUMENTATION_NAME, 'Patching server.emit');
313313

314314
// eslint-disable-next-line @typescript-eslint/no-this-alias
315315
const instrumentation = this;
@@ -322,7 +322,7 @@ export class SentryHttpInstrumentation extends InstrumentationBase<SentryHttpIns
322322
return target.apply(thisArg, args);
323323
}
324324

325-
DEBUG_BUILD && logger.log(INSTRUMENTATION_NAME, 'Handling incoming request');
325+
DEBUG_BUILD && debug.log(INSTRUMENTATION_NAME, 'Handling incoming request');
326326

327327
const isolationScope = getIsolationScope().clone();
328328
const request = args[1] as http.IncomingMessage;
@@ -467,7 +467,7 @@ function patchRequestToCaptureBody(
467467
let bodyByteLength = 0;
468468
const chunks: Buffer[] = [];
469469

470-
DEBUG_BUILD && logger.log(INSTRUMENTATION_NAME, 'Patching request.on');
470+
DEBUG_BUILD && debug.log(INSTRUMENTATION_NAME, 'Patching request.on');
471471

472472
/**
473473
* We need to keep track of the original callbacks, in order to be able to remove listeners again.
@@ -491,7 +491,7 @@ function patchRequestToCaptureBody(
491491

492492
if (event === 'data') {
493493
DEBUG_BUILD &&
494-
logger.log(INSTRUMENTATION_NAME, `Handling request.on("data") with maximum body size of ${maxBodySize}b`);
494+
debug.log(INSTRUMENTATION_NAME, `Handling request.on("data") with maximum body size of ${maxBodySize}b`);
495495

496496
const callback = new Proxy(listener, {
497497
apply: (target, thisArg, args: Parameters<typeof listener>) => {
@@ -503,13 +503,13 @@ function patchRequestToCaptureBody(
503503
chunks.push(bufferifiedChunk);
504504
bodyByteLength += bufferifiedChunk.byteLength;
505505
} else if (DEBUG_BUILD) {
506-
logger.log(
506+
debug.log(
507507
INSTRUMENTATION_NAME,
508508
`Dropping request body chunk because maximum body length of ${maxBodySize}b is exceeded.`,
509509
);
510510
}
511511
} catch (err) {
512-
DEBUG_BUILD && logger.error(INSTRUMENTATION_NAME, 'Encountered error while storing body chunk.');
512+
DEBUG_BUILD && debug.error(INSTRUMENTATION_NAME, 'Encountered error while storing body chunk.');
513513
}
514514

515515
return Reflect.apply(target, thisArg, args);
@@ -561,13 +561,13 @@ function patchRequestToCaptureBody(
561561
}
562562
} catch (error) {
563563
if (DEBUG_BUILD) {
564-
logger.error(INSTRUMENTATION_NAME, 'Error building captured request body', error);
564+
debug.error(INSTRUMENTATION_NAME, 'Error building captured request body', error);
565565
}
566566
}
567567
});
568568
} catch (error) {
569569
if (DEBUG_BUILD) {
570-
logger.error(INSTRUMENTATION_NAME, 'Error patching request to capture body', error);
570+
debug.error(INSTRUMENTATION_NAME, 'Error patching request to capture body', error);
571571
}
572572
}
573573
}
@@ -611,7 +611,7 @@ export function recordRequestSession({
611611
const requestSession = requestIsolationScope.getScopeData().sdkProcessingMetadata.requestSession;
612612

613613
if (client && requestSession) {
614-
DEBUG_BUILD && logger.debug(`Recorded request session with status: ${requestSession.status}`);
614+
DEBUG_BUILD && debug.log(`Recorded request session with status: ${requestSession.status}`);
615615

616616
const roundedDate = new Date();
617617
roundedDate.setSeconds(0, 0);
@@ -624,7 +624,7 @@ export function recordRequestSession({
624624
if (existingClientAggregate) {
625625
existingClientAggregate[dateBucketKey] = bucket;
626626
} else {
627-
DEBUG_BUILD && logger.debug('Opened new request session aggregate.');
627+
DEBUG_BUILD && debug.log('Opened new request session aggregate.');
628628
const newClientAggregate = { [dateBucketKey]: bucket };
629629
clientToRequestSessionAggregatesMap.set(client, newClientAggregate);
630630

@@ -645,11 +645,11 @@ export function recordRequestSession({
645645
};
646646

647647
const unregisterClientFlushHook = client.on('flush', () => {
648-
DEBUG_BUILD && logger.debug('Sending request session aggregate due to client flush');
648+
DEBUG_BUILD && debug.log('Sending request session aggregate due to client flush');
649649
flushPendingClientAggregates();
650650
});
651651
const timeout = setTimeout(() => {
652-
DEBUG_BUILD && logger.debug('Sending request session aggregate due to flushing schedule');
652+
DEBUG_BUILD && debug.log('Sending request session aggregate due to flushing schedule');
653653
flushPendingClientAggregates();
654654
}, sessionFlushingDelayMS).unref();
655655
}

packages/node-core/src/integrations/local-variables/local-variables-async.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { Worker } from 'node:worker_threads';
22
import type { Event, EventHint, Exception, IntegrationFn } from '@sentry/core';
3-
import { defineIntegration, logger } from '@sentry/core';
3+
import { debug, defineIntegration } from '@sentry/core';
44
import type { NodeClient } from '../../sdk/client';
55
import { isDebuggerEnabled } from '../../utils/debug';
66
import type { FrameVariables, LocalVariablesIntegrationOptions, LocalVariablesWorkerArgs } from './common';
@@ -10,7 +10,7 @@ import { functionNamesMatch, LOCAL_VARIABLES_KEY } from './common';
1010
export const base64WorkerScript = '###LocalVariablesWorkerScript###';
1111

1212
function log(...args: unknown[]): void {
13-
logger.log('[LocalVariables]', ...args);
13+
debug.log('[LocalVariables]', ...args);
1414
}
1515

1616
/**
@@ -111,25 +111,25 @@ export const localVariablesAsyncIntegration = defineIntegration(((
111111
}
112112

113113
if (await isDebuggerEnabled()) {
114-
logger.warn('Local variables capture has been disabled because the debugger was already enabled');
114+
debug.warn('Local variables capture has been disabled because the debugger was already enabled');
115115
return;
116116
}
117117

118118
const options: LocalVariablesWorkerArgs = {
119119
...integrationOptions,
120-
debug: logger.isEnabled(),
120+
debug: debug.isEnabled(),
121121
};
122122

123123
startInspector().then(
124124
() => {
125125
try {
126126
startWorker(options);
127127
} catch (e) {
128-
logger.error('Failed to start worker', e);
128+
debug.error('Failed to start worker', e);
129129
}
130130
},
131131
e => {
132-
logger.error('Failed to start inspector', e);
132+
debug.error('Failed to start inspector', e);
133133
},
134134
);
135135
},

packages/node-core/src/integrations/local-variables/local-variables-sync.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import type { Debugger, InspectorNotification, Runtime, Session } from 'node:inspector';
22
import type { Event, Exception, IntegrationFn, StackFrame, StackParser } from '@sentry/core';
3-
import { defineIntegration, getClient, logger, LRUMap } from '@sentry/core';
3+
import { debug, defineIntegration, getClient, LRUMap } from '@sentry/core';
44
import { NODE_MAJOR } from '../../nodeVersion';
55
import type { NodeClient } from '../../sdk/client';
66
import { isDebuggerEnabled } from '../../utils/debug';
@@ -303,12 +303,12 @@ const _localVariablesSyncIntegration = ((
303303
const unsupportedNodeVersion = NODE_MAJOR < 18;
304304

305305
if (unsupportedNodeVersion) {
306-
logger.log('The `LocalVariables` integration is only supported on Node >= v18.');
306+
debug.log('The `LocalVariables` integration is only supported on Node >= v18.');
307307
return;
308308
}
309309

310310
if (await isDebuggerEnabled()) {
311-
logger.warn('Local variables capture has been disabled because the debugger was already enabled');
311+
debug.warn('Local variables capture has been disabled because the debugger was already enabled');
312312
return;
313313
}
314314

@@ -384,11 +384,11 @@ const _localVariablesSyncIntegration = ((
384384
rateLimiter = createRateLimiter(
385385
max,
386386
() => {
387-
logger.log('Local variables rate-limit lifted.');
387+
debug.log('Local variables rate-limit lifted.');
388388
session.setPauseOnExceptions(true);
389389
},
390390
seconds => {
391-
logger.log(
391+
debug.log(
392392
`Local variables rate-limit exceeded. Disabling capturing of caught exceptions for ${seconds} seconds.`,
393393
);
394394
session.setPauseOnExceptions(false);
@@ -399,7 +399,7 @@ const _localVariablesSyncIntegration = ((
399399
shouldProcessEvent = true;
400400
},
401401
error => {
402-
logger.log('The `LocalVariables` integration failed to start.', error);
402+
debug.log('The `LocalVariables` integration failed to start.', error);
403403
},
404404
);
405405
},

packages/node-core/src/integrations/onuncaughtexception.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { captureException, defineIntegration, getClient, logger } from '@sentry/core';
1+
import { captureException, debug, defineIntegration, getClient } from '@sentry/core';
22
import { DEBUG_BUILD } from '../debug-build';
33
import type { NodeClient } from '../sdk/client';
44
import { logAndExitProcess } from '../utils/errorhandling';
@@ -122,7 +122,7 @@ export function makeErrorHandler(client: NodeClient, options: OnUncaughtExceptio
122122
if (calledFatalError) {
123123
// we hit an error *after* calling onFatalError - pretty boned at this point, just shut it down
124124
DEBUG_BUILD &&
125-
logger.warn(
125+
debug.warn(
126126
'uncaught exception after calling fatal error shutdown callback - this is bad! forcing shutdown',
127127
);
128128
logAndExitProcess(error);

packages/node-core/src/integrations/spotlight.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import * as http from 'node:http';
22
import type { Client, Envelope, IntegrationFn } from '@sentry/core';
3-
import { defineIntegration, logger, serializeEnvelope, suppressTracing } from '@sentry/core';
3+
import { debug, defineIntegration, serializeEnvelope, suppressTracing } from '@sentry/core';
44

55
type SpotlightConnectionOptions = {
66
/**
@@ -22,7 +22,7 @@ const _spotlightIntegration = ((options: Partial<SpotlightConnectionOptions> = {
2222
setup(client) {
2323
try {
2424
if (process.env.NODE_ENV && process.env.NODE_ENV !== 'development') {
25-
logger.warn("[Spotlight] It seems you're not in dev mode. Do you really want to have Spotlight enabled?");
25+
debug.warn("[Spotlight] It seems you're not in dev mode. Do you really want to have Spotlight enabled?");
2626
}
2727
} catch {
2828
// ignore
@@ -51,7 +51,7 @@ function connectToSpotlight(client: Client, options: Required<SpotlightConnectio
5151

5252
client.on('beforeEnvelope', (envelope: Envelope) => {
5353
if (failedRequests > 3) {
54-
logger.warn('[Spotlight] Disabled Sentry -> Spotlight integration due to too many failed requests');
54+
debug.warn('[Spotlight] Disabled Sentry -> Spotlight integration due to too many failed requests');
5555
return;
5656
}
5757

@@ -85,7 +85,7 @@ function connectToSpotlight(client: Client, options: Required<SpotlightConnectio
8585

8686
req.on('error', () => {
8787
failedRequests++;
88-
logger.warn('[Spotlight] Failed to send envelope to Spotlight Sidecar');
88+
debug.warn('[Spotlight] Failed to send envelope to Spotlight Sidecar');
8989
});
9090
req.write(serializedEnvelope);
9191
req.end();
@@ -97,7 +97,7 @@ function parseSidecarUrl(url: string): URL | undefined {
9797
try {
9898
return new URL(`${url}`);
9999
} catch {
100-
logger.warn(`[Spotlight] Invalid sidecar URL: ${url}`);
100+
debug.warn(`[Spotlight] Invalid sidecar URL: ${url}`);
101101
return undefined;
102102
}
103103
}

0 commit comments

Comments
 (0)