Skip to content

ref(node-core|node): Use debug instead of logger #17025

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

Merged
merged 5 commits into from
Jul 16, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions packages/node-core/src/integrations/anr/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ import { types } from 'node:util';
import { Worker } from 'node:worker_threads';
import type { Contexts, Event, EventHint, Integration, IntegrationFn, ScopeData } from '@sentry/core';
import {
debug,
defineIntegration,
getClient,
getCurrentScope,
getFilenameToDebugIdMap,
getGlobalScope,
getIsolationScope,
GLOBAL_OBJ,
logger,
mergeScopeData,
} from '@sentry/core';
import { NODE_VERSION } from '../../nodeVersion';
Expand All @@ -26,7 +26,7 @@ const DEFAULT_INTERVAL = 50;
const DEFAULT_HANG_THRESHOLD = 5000;

function log(message: string, ...args: unknown[]): void {
logger.log(`[ANR] ${message}`, ...args);
debug.log(`[ANR] ${message}`, ...args);
}

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

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

Expand Down Expand Up @@ -188,7 +188,7 @@ async function _startWorker(
}

const options: WorkerStartData = {
debug: logger.isEnabled(),
debug: debug.isEnabled(),
dsn,
tunnel: initOptions.tunnel,
environment: initOptions.environment || 'production',
Expand Down
12 changes: 6 additions & 6 deletions packages/node-core/src/integrations/contextlines.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { createReadStream } from 'node:fs';
import { createInterface } from 'node:readline';
import type { Event, IntegrationFn, StackFrame } from '@sentry/core';
import { defineIntegration, logger, LRUMap, snipLine } from '@sentry/core';
import { debug, defineIntegration, LRUMap, snipLine } from '@sentry/core';
import { DEBUG_BUILD } from '../debug-build';

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

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

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

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

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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import type { AggregationCounts, Client, SanitizedRequestData, Scope } from '@se
import {
addBreadcrumb,
addNonEnumerableProperty,
debug,
generateSpanId,
getBreadcrumbLogLevelFromHttpStatusCode,
getClient,
Expand All @@ -21,7 +22,6 @@ import {
getTraceData,
httpRequestToRequestData,
isError,
logger,
LRUMap,
parseUrl,
SDK_VERSION,
Expand Down Expand Up @@ -219,7 +219,7 @@ export class SentryHttpInstrumentation extends InstrumentationBase<SentryHttpIns
* It has access to the final request and response objects.
*/
private _onOutgoingRequestFinish(request: http.ClientRequest, response?: http.IncomingMessage): void {
DEBUG_BUILD && logger.log(INSTRUMENTATION_NAME, 'Handling finished outgoing request');
DEBUG_BUILD && debug.log(INSTRUMENTATION_NAME, 'Handling finished outgoing request');

const _breadcrumbs = this.getConfig().breadcrumbs;
const breadCrumbsEnabled = typeof _breadcrumbs === 'undefined' ? true : _breadcrumbs;
Expand Down Expand Up @@ -266,10 +266,10 @@ export class SentryHttpInstrumentation extends InstrumentationBase<SentryHttpIns
if (sentryTrace && !request.getHeader('sentry-trace')) {
try {
request.setHeader('sentry-trace', sentryTrace);
DEBUG_BUILD && logger.log(INSTRUMENTATION_NAME, 'Added sentry-trace header to outgoing request');
DEBUG_BUILD && debug.log(INSTRUMENTATION_NAME, 'Added sentry-trace header to outgoing request');
} catch (error) {
DEBUG_BUILD &&
logger.error(
debug.error(
INSTRUMENTATION_NAME,
'Failed to add sentry-trace header to outgoing request:',
isError(error) ? error.message : 'Unknown error',
Expand All @@ -283,10 +283,10 @@ export class SentryHttpInstrumentation extends InstrumentationBase<SentryHttpIns
if (newBaggage) {
try {
request.setHeader('baggage', newBaggage);
DEBUG_BUILD && logger.log(INSTRUMENTATION_NAME, 'Added baggage header to outgoing request');
DEBUG_BUILD && debug.log(INSTRUMENTATION_NAME, 'Added baggage header to outgoing request');
} catch (error) {
DEBUG_BUILD &&
logger.error(
debug.error(
INSTRUMENTATION_NAME,
'Failed to add baggage header to outgoing request:',
isError(error) ? error.message : 'Unknown error',
Expand All @@ -309,7 +309,7 @@ export class SentryHttpInstrumentation extends InstrumentationBase<SentryHttpIns
return;
}

DEBUG_BUILD && logger.log(INSTRUMENTATION_NAME, 'Patching server.emit');
DEBUG_BUILD && debug.log(INSTRUMENTATION_NAME, 'Patching server.emit');

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

DEBUG_BUILD && logger.log(INSTRUMENTATION_NAME, 'Handling incoming request');
DEBUG_BUILD && debug.log(INSTRUMENTATION_NAME, 'Handling incoming request');

const isolationScope = getIsolationScope().clone();
const request = args[1] as http.IncomingMessage;
Expand Down Expand Up @@ -467,7 +467,7 @@ function patchRequestToCaptureBody(
let bodyByteLength = 0;
const chunks: Buffer[] = [];

DEBUG_BUILD && logger.log(INSTRUMENTATION_NAME, 'Patching request.on');
DEBUG_BUILD && debug.log(INSTRUMENTATION_NAME, 'Patching request.on');

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

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

const callback = new Proxy(listener, {
apply: (target, thisArg, args: Parameters<typeof listener>) => {
Expand All @@ -503,13 +503,13 @@ function patchRequestToCaptureBody(
chunks.push(bufferifiedChunk);
bodyByteLength += bufferifiedChunk.byteLength;
} else if (DEBUG_BUILD) {
logger.log(
debug.log(
INSTRUMENTATION_NAME,
`Dropping request body chunk because maximum body length of ${maxBodySize}b is exceeded.`,
);
}
} catch (err) {
DEBUG_BUILD && logger.error(INSTRUMENTATION_NAME, 'Encountered error while storing body chunk.');
DEBUG_BUILD && debug.error(INSTRUMENTATION_NAME, 'Encountered error while storing body chunk.');
}

return Reflect.apply(target, thisArg, args);
Expand Down Expand Up @@ -561,13 +561,13 @@ function patchRequestToCaptureBody(
}
} catch (error) {
if (DEBUG_BUILD) {
logger.error(INSTRUMENTATION_NAME, 'Error building captured request body', error);
debug.error(INSTRUMENTATION_NAME, 'Error building captured request body', error);
}
}
});
} catch (error) {
if (DEBUG_BUILD) {
logger.error(INSTRUMENTATION_NAME, 'Error patching request to capture body', error);
debug.error(INSTRUMENTATION_NAME, 'Error patching request to capture body', error);
}
}
}
Expand Down Expand Up @@ -611,7 +611,7 @@ export function recordRequestSession({
const requestSession = requestIsolationScope.getScopeData().sdkProcessingMetadata.requestSession;

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

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

Expand All @@ -645,11 +645,11 @@ export function recordRequestSession({
};

const unregisterClientFlushHook = client.on('flush', () => {
DEBUG_BUILD && logger.debug('Sending request session aggregate due to client flush');
DEBUG_BUILD && debug.log('Sending request session aggregate due to client flush');
flushPendingClientAggregates();
});
const timeout = setTimeout(() => {
DEBUG_BUILD && logger.debug('Sending request session aggregate due to flushing schedule');
DEBUG_BUILD && debug.log('Sending request session aggregate due to flushing schedule');
flushPendingClientAggregates();
}, sessionFlushingDelayMS).unref();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Worker } from 'node:worker_threads';
import type { Event, EventHint, Exception, IntegrationFn } from '@sentry/core';
import { defineIntegration, logger } from '@sentry/core';
import { debug, defineIntegration } from '@sentry/core';
import type { NodeClient } from '../../sdk/client';
import { isDebuggerEnabled } from '../../utils/debug';
import type { FrameVariables, LocalVariablesIntegrationOptions, LocalVariablesWorkerArgs } from './common';
Expand All @@ -10,7 +10,7 @@ import { functionNamesMatch, LOCAL_VARIABLES_KEY } from './common';
export const base64WorkerScript = '###LocalVariablesWorkerScript###';

function log(...args: unknown[]): void {
logger.log('[LocalVariables]', ...args);
debug.log('[LocalVariables]', ...args);
}

/**
Expand Down Expand Up @@ -111,25 +111,25 @@ export const localVariablesAsyncIntegration = defineIntegration(((
}

if (await isDebuggerEnabled()) {
logger.warn('Local variables capture has been disabled because the debugger was already enabled');
debug.warn('Local variables capture has been disabled because the debugger was already enabled');
return;
}

const options: LocalVariablesWorkerArgs = {
...integrationOptions,
debug: logger.isEnabled(),
debug: debug.isEnabled(),
};

startInspector().then(
() => {
try {
startWorker(options);
} catch (e) {
logger.error('Failed to start worker', e);
debug.error('Failed to start worker', e);
}
},
e => {
logger.error('Failed to start inspector', e);
debug.error('Failed to start inspector', e);
},
);
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { Debugger, InspectorNotification, Runtime, Session } from 'node:inspector';
import type { Event, Exception, IntegrationFn, StackFrame, StackParser } from '@sentry/core';
import { defineIntegration, getClient, logger, LRUMap } from '@sentry/core';
import { debug, defineIntegration, getClient, LRUMap } from '@sentry/core';
import { NODE_MAJOR } from '../../nodeVersion';
import type { NodeClient } from '../../sdk/client';
import { isDebuggerEnabled } from '../../utils/debug';
Expand Down Expand Up @@ -303,12 +303,12 @@ const _localVariablesSyncIntegration = ((
const unsupportedNodeVersion = NODE_MAJOR < 18;

if (unsupportedNodeVersion) {
logger.log('The `LocalVariables` integration is only supported on Node >= v18.');
debug.log('The `LocalVariables` integration is only supported on Node >= v18.');
return;
}

if (await isDebuggerEnabled()) {
logger.warn('Local variables capture has been disabled because the debugger was already enabled');
debug.warn('Local variables capture has been disabled because the debugger was already enabled');
return;
}

Expand Down Expand Up @@ -384,11 +384,11 @@ const _localVariablesSyncIntegration = ((
rateLimiter = createRateLimiter(
max,
() => {
logger.log('Local variables rate-limit lifted.');
debug.log('Local variables rate-limit lifted.');
session.setPauseOnExceptions(true);
},
seconds => {
logger.log(
debug.log(
`Local variables rate-limit exceeded. Disabling capturing of caught exceptions for ${seconds} seconds.`,
);
session.setPauseOnExceptions(false);
Expand All @@ -399,7 +399,7 @@ const _localVariablesSyncIntegration = ((
shouldProcessEvent = true;
},
error => {
logger.log('The `LocalVariables` integration failed to start.', error);
debug.log('The `LocalVariables` integration failed to start.', error);
},
);
},
Expand Down
4 changes: 2 additions & 2 deletions packages/node-core/src/integrations/onuncaughtexception.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { captureException, defineIntegration, getClient, logger } from '@sentry/core';
import { captureException, debug, defineIntegration, getClient } from '@sentry/core';
import { DEBUG_BUILD } from '../debug-build';
import type { NodeClient } from '../sdk/client';
import { logAndExitProcess } from '../utils/errorhandling';
Expand Down Expand Up @@ -122,7 +122,7 @@ export function makeErrorHandler(client: NodeClient, options: OnUncaughtExceptio
if (calledFatalError) {
// we hit an error *after* calling onFatalError - pretty boned at this point, just shut it down
DEBUG_BUILD &&
logger.warn(
debug.warn(
'uncaught exception after calling fatal error shutdown callback - this is bad! forcing shutdown',
);
logAndExitProcess(error);
Expand Down
10 changes: 5 additions & 5 deletions packages/node-core/src/integrations/spotlight.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as http from 'node:http';
import type { Client, Envelope, IntegrationFn } from '@sentry/core';
import { defineIntegration, logger, serializeEnvelope, suppressTracing } from '@sentry/core';
import { debug, defineIntegration, serializeEnvelope, suppressTracing } from '@sentry/core';

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

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

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

req.on('error', () => {
failedRequests++;
logger.warn('[Spotlight] Failed to send envelope to Spotlight Sidecar');
debug.warn('[Spotlight] Failed to send envelope to Spotlight Sidecar');
});
req.write(serializedEnvelope);
req.end();
Expand All @@ -97,7 +97,7 @@ function parseSidecarUrl(url: string): URL | undefined {
try {
return new URL(`${url}`);
} catch {
logger.warn(`[Spotlight] Invalid sidecar URL: ${url}`);
debug.warn(`[Spotlight] Invalid sidecar URL: ${url}`);
return undefined;
}
}
Loading
Loading