From 928e27e704f7bc63819d4a42844ac78a541c1915 Mon Sep 17 00:00:00 2001 From: Katie Byers Date: Wed, 9 Mar 2022 04:43:00 -0800 Subject: [PATCH 1/4] convert `isDebugBuild` checks from `if` blocks to short-circuits --- packages/browser/src/helpers.ts | 8 ++------ .../src/integrations/globalhandlers.ts | 4 +--- packages/browser/src/sdk.ts | 12 +++-------- packages/browser/src/transports/utils.ts | 3 +-- packages/core/src/basebackend.ts | 12 +++-------- packages/core/src/baseclient.ts | 8 ++------ .../core/src/integrations/inboundfilters.ts | 20 ++++++------------- packages/utils/src/instrument.ts | 3 +-- packages/utils/src/supports.ts | 3 +-- 9 files changed, 20 insertions(+), 53 deletions(-) diff --git a/packages/browser/src/helpers.ts b/packages/browser/src/helpers.ts index 622094d73054..46a8919ee7c6 100644 --- a/packages/browser/src/helpers.ts +++ b/packages/browser/src/helpers.ts @@ -192,16 +192,12 @@ export function injectReportDialog(options: ReportDialogOptions = {}): void { } if (!options.eventId) { - if (isDebugBuild()) { - logger.error('Missing eventId option in showReportDialog call'); - } + isDebugBuild() && logger.error('Missing eventId option in showReportDialog call'); return; } if (!options.dsn) { - if (isDebugBuild()) { - logger.error('Missing dsn option in showReportDialog call'); - } + isDebugBuild() && logger.error('Missing dsn option in showReportDialog call'); return; } diff --git a/packages/browser/src/integrations/globalhandlers.ts b/packages/browser/src/integrations/globalhandlers.ts index c3cb56a8f341..09ee6f16a643 100644 --- a/packages/browser/src/integrations/globalhandlers.ts +++ b/packages/browser/src/integrations/globalhandlers.ts @@ -237,9 +237,7 @@ function _enhanceEventWithInitialFrame(event: Event, url: any, line: any, column } function globalHandlerLog(type: string): void { - if (isDebugBuild()) { - logger.log(`Global Handler attached: ${type}`); - } + isDebugBuild() && logger.log(`Global Handler attached: ${type}`); } function addMechanismAndCapture(hub: Hub, error: EventHint['originalException'], event: Event, type: string): void { diff --git a/packages/browser/src/sdk.ts b/packages/browser/src/sdk.ts index ed3f0c8ba888..f776df5a8392 100644 --- a/packages/browser/src/sdk.ts +++ b/packages/browser/src/sdk.ts @@ -162,9 +162,7 @@ export function flush(timeout?: number): PromiseLike { if (client) { return client.flush(timeout); } - if (isDebugBuild()) { - logger.warn('Cannot flush events. No client defined.'); - } + isDebugBuild() && logger.warn('Cannot flush events. No client defined.'); return resolvedSyncPromise(false); } @@ -181,9 +179,7 @@ export function close(timeout?: number): PromiseLike { if (client) { return client.close(timeout); } - if (isDebugBuild()) { - logger.warn('Cannot flush events and disable SDK. No client defined.'); - } + isDebugBuild() && logger.warn('Cannot flush events and disable SDK. No client defined.'); return resolvedSyncPromise(false); } @@ -212,9 +208,7 @@ function startSessionTracking(): void { const document = window.document; if (typeof document === 'undefined') { - if (isDebugBuild()) { - logger.warn('Session tracking in non-browser environment with @sentry/browser is not supported.'); - } + isDebugBuild() && logger.warn('Session tracking in non-browser environment with @sentry/browser is not supported.'); return; } diff --git a/packages/browser/src/transports/utils.ts b/packages/browser/src/transports/utils.ts index a6f9cb5a726d..962a05208466 100644 --- a/packages/browser/src/transports/utils.ts +++ b/packages/browser/src/transports/utils.ts @@ -69,9 +69,8 @@ export function getNativeFetchImplementation(): FetchImpl { } document.head.removeChild(sandbox); } catch (e) { - if (isDebugBuild()) { + isDebugBuild() && logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', e); - } } } diff --git a/packages/core/src/basebackend.ts b/packages/core/src/basebackend.ts index 83aca1565c9f..b69a9ce898fd 100644 --- a/packages/core/src/basebackend.ts +++ b/packages/core/src/basebackend.ts @@ -92,9 +92,7 @@ export abstract class BaseBackend implements Backend { */ public sendEvent(event: Event): void { void this._transport.sendEvent(event).then(null, reason => { - if (isDebugBuild()) { - logger.error('Error while sending event:', reason); - } + isDebugBuild() && logger.error('Error while sending event:', reason); }); } @@ -103,16 +101,12 @@ export abstract class BaseBackend implements Backend { */ public sendSession(session: Session): void { if (!this._transport.sendSession) { - if (isDebugBuild()) { - logger.warn("Dropping session because custom transport doesn't implement sendSession"); - } + isDebugBuild() && logger.warn("Dropping session because custom transport doesn't implement sendSession"); return; } void this._transport.sendSession(session).then(null, reason => { - if (isDebugBuild()) { - logger.error('Error while sending session:', reason); - } + isDebugBuild() && logger.error('Error while sending session:', reason); }); } diff --git a/packages/core/src/baseclient.ts b/packages/core/src/baseclient.ts index b831284d221f..0e6c61c33cfc 100644 --- a/packages/core/src/baseclient.ts +++ b/packages/core/src/baseclient.ts @@ -173,16 +173,12 @@ export abstract class BaseClient implement */ public captureSession(session: Session): void { if (!this._isEnabled()) { - if (isDebugBuild()) { - logger.warn('SDK not enabled, will not capture session.'); - } + isDebugBuild() && logger.warn('SDK not enabled, will not capture session.'); return; } if (!(typeof session.release === 'string')) { - if (isDebugBuild()) { - logger.warn('Discarded session because of missing or non-string release'); - } + isDebugBuild() && logger.warn('Discarded session because of missing or non-string release'); } else { this._sendSession(session); // After sending, we set init false to indicate it's not the first occurrence diff --git a/packages/core/src/integrations/inboundfilters.ts b/packages/core/src/integrations/inboundfilters.ts index f779c3be6266..6a2cf7133f8b 100644 --- a/packages/core/src/integrations/inboundfilters.ts +++ b/packages/core/src/integrations/inboundfilters.ts @@ -64,37 +64,33 @@ export class InboundFilters implements Integration { /** JSDoc */ private _shouldDropEvent(event: Event, options: Partial): boolean { if (this._isSentryError(event, options)) { - if (isDebugBuild()) { + isDebugBuild() && logger.warn(`Event dropped due to being internal Sentry Error.\nEvent: ${getEventDescription(event)}`); - } return true; } if (this._isIgnoredError(event, options)) { - if (isDebugBuild()) { + isDebugBuild() && logger.warn( `Event dropped due to being matched by \`ignoreErrors\` option.\nEvent: ${getEventDescription(event)}`, ); - } return true; } if (this._isDeniedUrl(event, options)) { - if (isDebugBuild()) { + isDebugBuild() && logger.warn( `Event dropped due to being matched by \`denyUrls\` option.\nEvent: ${getEventDescription( event, )}.\nUrl: ${this._getEventFilterUrl(event)}`, ); - } return true; } if (!this._isAllowedUrl(event, options)) { - if (isDebugBuild()) { + isDebugBuild() && logger.warn( `Event dropped due to not being matched by \`allowUrls\` option.\nEvent: ${getEventDescription( event, )}.\nUrl: ${this._getEventFilterUrl(event)}`, ); - } return true; } return false; @@ -187,9 +183,7 @@ export class InboundFilters implements Integration { const { type = '', value = '' } = (event.exception.values && event.exception.values[0]) || {}; return [`${value}`, `${type}: ${value}`]; } catch (oO) { - if (isDebugBuild()) { - logger.error(`Cannot extract message for event ${getEventDescription(event)}`); - } + isDebugBuild() && logger.error(`Cannot extract message for event ${getEventDescription(event)}`); return []; } } @@ -224,9 +218,7 @@ export class InboundFilters implements Integration { } return frames ? this._getLastValidUrl(frames) : null; } catch (oO) { - if (isDebugBuild()) { - logger.error(`Cannot extract url for event ${getEventDescription(event)}`); - } + isDebugBuild() && logger.error(`Cannot extract url for event ${getEventDescription(event)}`); return null; } } diff --git a/packages/utils/src/instrument.ts b/packages/utils/src/instrument.ts index 74b907a00c2d..78938468453c 100644 --- a/packages/utils/src/instrument.ts +++ b/packages/utils/src/instrument.ts @@ -94,12 +94,11 @@ function triggerHandlers(type: InstrumentHandlerType, data: any): void { try { handler(data); } catch (e) { - if (isDebugBuild()) { + isDebugBuild() && logger.error( `Error while triggering instrumentation handler.\nType: ${type}\nName: ${getFunctionName(handler)}\nError:`, e, ); - } } } } diff --git a/packages/utils/src/supports.ts b/packages/utils/src/supports.ts index 1c55d06e0dee..59e6bd6804c8 100644 --- a/packages/utils/src/supports.ts +++ b/packages/utils/src/supports.ts @@ -113,9 +113,8 @@ export function supportsNativeFetch(): boolean { } doc.head.removeChild(sandbox); } catch (err) { - if (isDebugBuild()) { + isDebugBuild() && logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err); - } } } From a188c9a48c5754568857d3a23ce78e7a82de92c1 Mon Sep 17 00:00:00 2001 From: Katie Byers Date: Wed, 9 Mar 2022 04:08:26 -0800 Subject: [PATCH 2/4] add debug guards to remaining calls to logger methods --- packages/angular/src/tracing.ts | 5 +- packages/browser/src/client.ts | 4 +- packages/browser/src/integrations/dedupe.ts | 4 +- packages/browser/src/transports/base.ts | 13 +++--- packages/core/src/basebackend.ts | 2 +- packages/core/src/baseclient.ts | 8 ++-- packages/core/src/integration.ts | 4 +- packages/hub/src/hub.ts | 16 +++++-- packages/hub/src/sessionflusher.ts | 6 +-- packages/integrations/src/angular.ts | 6 +-- packages/integrations/src/dedupe.ts | 4 +- packages/integrations/src/ember.ts | 4 +- packages/integrations/src/extraerrordata.ts | 4 +- packages/integrations/src/offline.ts | 14 +++--- packages/integrations/src/vue.ts | 13 +++--- packages/nextjs/src/config/webpack.ts | 13 +++--- packages/nextjs/src/index.server.ts | 10 ++-- packages/nextjs/src/utils/instrumentServer.ts | 4 +- packages/nextjs/src/utils/withSentry.ts | 17 +++++-- packages/node/src/client.ts | 6 +-- packages/node/src/handlers.ts | 3 +- packages/node/src/integrations/http.ts | 9 ++-- .../src/integrations/onuncaughtexception.ts | 5 +- .../src/integrations/utils/errorhandling.ts | 6 +-- packages/node/src/sdk.ts | 6 +-- packages/node/src/transports/base/index.ts | 12 +++-- packages/react/src/errorboundary.tsx | 4 +- packages/serverless/src/awslambda.ts | 12 ++--- .../src/gcpfunction/cloud_events.ts | 4 +- packages/serverless/src/gcpfunction/events.ts | 4 +- packages/serverless/src/gcpfunction/http.ts | 4 +- packages/tracing/src/browser/backgroundtab.ts | 11 +++-- .../tracing/src/browser/browsertracing.ts | 23 ++++++---- packages/tracing/src/browser/metrics.ts | 30 +++++++----- packages/tracing/src/browser/router.ts | 6 +-- packages/tracing/src/errors.ts | 4 +- packages/tracing/src/hubextensions.ts | 46 ++++++++++--------- packages/tracing/src/idletransaction.ts | 37 ++++++++------- .../tracing/src/integrations/node/express.ts | 4 +- .../tracing/src/integrations/node/mongo.ts | 4 +- .../tracing/src/integrations/node/mysql.ts | 4 +- .../tracing/src/integrations/node/postgres.ts | 6 +-- packages/tracing/src/transaction.ts | 14 ++++-- packages/utils/src/instrument.ts | 3 +- packages/vue/src/sdk.ts | 13 +++--- packages/vue/src/tracing.ts | 4 +- 46 files changed, 242 insertions(+), 193 deletions(-) diff --git a/packages/angular/src/tracing.ts b/packages/angular/src/tracing.ts index d34edc5407bc..df45270f14d3 100644 --- a/packages/angular/src/tracing.ts +++ b/packages/angular/src/tracing.ts @@ -2,7 +2,7 @@ import { AfterViewInit, Directive, Injectable, Input, NgModule, OnDestroy, OnIni import { Event, NavigationEnd, NavigationStart, Router } from '@angular/router'; import { getCurrentHub } from '@sentry/browser'; import { Span, Transaction, TransactionContext } from '@sentry/types'; -import { getGlobalObject, logger, stripUrlQueryAndFragment, timestampWithMs } from '@sentry/utils'; +import { getGlobalObject, isDebugBuild, logger, stripUrlQueryAndFragment, timestampWithMs } from '@sentry/utils'; import { Observable, Subscription } from 'rxjs'; import { filter, tap } from 'rxjs/operators'; @@ -63,7 +63,8 @@ export class TraceService implements OnDestroy { filter(event => event instanceof NavigationStart), tap(event => { if (!instrumentationInitialized) { - logger.error('Angular integration has tracing enabled, but Tracing integration is not configured'); + isDebugBuild() && + logger.error('Angular integration has tracing enabled, but Tracing integration is not configured'); return; } diff --git a/packages/browser/src/client.ts b/packages/browser/src/client.ts index aeb1539e2a7d..e036e5d67879 100644 --- a/packages/browser/src/client.ts +++ b/packages/browser/src/client.ts @@ -1,6 +1,6 @@ import { BaseClient, Scope, SDK_VERSION } from '@sentry/core'; import { Event, EventHint } from '@sentry/types'; -import { getGlobalObject, logger } from '@sentry/utils'; +import { getGlobalObject, isDebugBuild, logger } from '@sentry/utils'; import { BrowserBackend, BrowserOptions } from './backend'; import { injectReportDialog, ReportDialogOptions } from './helpers'; @@ -47,7 +47,7 @@ export class BrowserClient extends BaseClient { } if (!this._isEnabled()) { - logger.error('Trying to call showReportDialog with Sentry Client disabled'); + isDebugBuild() && logger.error('Trying to call showReportDialog with Sentry Client disabled'); return; } diff --git a/packages/browser/src/integrations/dedupe.ts b/packages/browser/src/integrations/dedupe.ts index 27cc80201694..e2e22c3975cd 100644 --- a/packages/browser/src/integrations/dedupe.ts +++ b/packages/browser/src/integrations/dedupe.ts @@ -1,5 +1,5 @@ import { Event, EventProcessor, Exception, Hub, Integration, StackFrame } from '@sentry/types'; -import { logger } from '@sentry/utils'; +import { isDebugBuild, logger } from '@sentry/utils'; /** Deduplication filter */ export class Dedupe implements Integration { @@ -28,7 +28,7 @@ export class Dedupe implements Integration { // Juuust in case something goes wrong try { if (_shouldDropEvent(currentEvent, self._previousEvent)) { - logger.warn('Event dropped due to being a duplicate of previously captured event.'); + isDebugBuild() && logger.warn('Event dropped due to being a duplicate of previously captured event.'); return null; } } catch (_oO) { diff --git a/packages/browser/src/transports/base.ts b/packages/browser/src/transports/base.ts index 60dffda0c246..d8f96aee1243 100644 --- a/packages/browser/src/transports/base.ts +++ b/packages/browser/src/transports/base.ts @@ -105,7 +105,7 @@ export abstract class BaseTransport implements Transport { // A correct type for map-based implementation if we want to go that route // would be `Partial>>>` const key = `${requestTypeToCategory(category)}:${reason}`; - logger.log(`Adding outcome: ${key}`); + isDebugBuild() && logger.log(`Adding outcome: ${key}`); this._outcomes[key] = (this._outcomes[key] ?? 0) + 1; } @@ -122,11 +122,11 @@ export abstract class BaseTransport implements Transport { // Nothing to send if (!Object.keys(outcomes).length) { - logger.log('No outcomes to flush'); + isDebugBuild() && logger.log('No outcomes to flush'); return; } - logger.log(`Flushing outcomes:\n${JSON.stringify(outcomes, null, 2)}`); + isDebugBuild() && logger.log(`Flushing outcomes:\n${JSON.stringify(outcomes, null, 2)}`); const url = getEnvelopeEndpointWithUrlEncodedAuth(this._api.dsn, this._api.tunnel); @@ -144,7 +144,7 @@ export abstract class BaseTransport implements Transport { try { sendReport(url, serializeEnvelope(envelope)); } catch (e) { - logger.error(e); + isDebugBuild() && logger.error(e); } } @@ -170,8 +170,9 @@ export abstract class BaseTransport implements Transport { * https://developer.mozilla.org/en-US/docs/Web/API/Headers/get */ const limited = this._handleRateLimit(headers); - if (limited && isDebugBuild()) { - logger.warn(`Too many ${requestType} requests, backing off until: ${this._disabledUntil(requestType)}`); + if (limited) { + isDebugBuild() && + logger.warn(`Too many ${requestType} requests, backing off until: ${this._disabledUntil(requestType)}`); } if (status === 'success') { diff --git a/packages/core/src/basebackend.ts b/packages/core/src/basebackend.ts index b69a9ce898fd..4ba8cce63bd7 100644 --- a/packages/core/src/basebackend.ts +++ b/packages/core/src/basebackend.ts @@ -67,7 +67,7 @@ export abstract class BaseBackend implements Backend { public constructor(options: O) { this._options = options; if (!this._options.dsn) { - logger.warn('No DSN provided, backend will not do anything.'); + isDebugBuild() && logger.warn('No DSN provided, backend will not do anything.'); } this._transport = this._setupTransport(); } diff --git a/packages/core/src/baseclient.ts b/packages/core/src/baseclient.ts index 0e6c61c33cfc..39b4c90fad65 100644 --- a/packages/core/src/baseclient.ts +++ b/packages/core/src/baseclient.ts @@ -108,7 +108,7 @@ export abstract class BaseClient implement public captureException(exception: any, hint?: EventHint, scope?: Scope): string | undefined { // ensure we haven't captured this very object before if (checkOrSetAlreadyCaught(exception)) { - logger.log(ALREADY_SEEN_ERROR); + isDebugBuild() && logger.log(ALREADY_SEEN_ERROR); return; } @@ -153,7 +153,7 @@ export abstract class BaseClient implement public captureEvent(event: Event, hint?: EventHint, scope?: Scope): string | undefined { // ensure we haven't captured this very object before if (hint && hint.originalException && checkOrSetAlreadyCaught(hint.originalException)) { - logger.log(ALREADY_SEEN_ERROR); + isDebugBuild() && logger.log(ALREADY_SEEN_ERROR); return; } @@ -244,7 +244,7 @@ export abstract class BaseClient implement try { return (this._integrations[integration.id] as T) || null; } catch (_oO) { - logger.warn(`Cannot retrieve integration ${integration.id} from the current Client`); + isDebugBuild() && logger.warn(`Cannot retrieve integration ${integration.id} from the current Client`); return null; } } @@ -503,7 +503,7 @@ export abstract class BaseClient implement return finalEvent.event_id; }, reason => { - logger.error(reason); + isDebugBuild() && logger.error(reason); return undefined; }, ); diff --git a/packages/core/src/integration.ts b/packages/core/src/integration.ts index d6bf819a3269..6d8b9fe3fd50 100644 --- a/packages/core/src/integration.ts +++ b/packages/core/src/integration.ts @@ -1,6 +1,6 @@ import { addGlobalEventProcessor, getCurrentHub } from '@sentry/hub'; import { Integration, Options } from '@sentry/types'; -import { addNonEnumerableProperty, logger } from '@sentry/utils'; +import { addNonEnumerableProperty, isDebugBuild, logger } from '@sentry/utils'; export const installedIntegrations: string[] = []; @@ -59,7 +59,7 @@ export function setupIntegration(integration: Integration): void { } integration.setupOnce(addGlobalEventProcessor, getCurrentHub); installedIntegrations.push(integration.name); - logger.log(`Integration installed: ${integration.name}`); + isDebugBuild() && logger.log(`Integration installed: ${integration.name}`); } /** diff --git a/packages/hub/src/hub.ts b/packages/hub/src/hub.ts index 851a2161d0fe..22d284f54acd 100644 --- a/packages/hub/src/hub.ts +++ b/packages/hub/src/hub.ts @@ -20,7 +20,15 @@ import { TransactionContext, User, } from '@sentry/types'; -import { consoleSandbox, dateTimestampInSeconds, getGlobalObject, isNodeEnv, logger, uuid4 } from '@sentry/utils'; +import { + consoleSandbox, + dateTimestampInSeconds, + getGlobalObject, + isDebugBuild, + isNodeEnv, + logger, + uuid4, +} from '@sentry/utils'; import { Scope } from './scope'; import { Session } from './session'; @@ -371,7 +379,7 @@ export class Hub implements HubInterface { try { return client.getIntegration(integration); } catch (_oO) { - logger.warn(`Cannot retrieve integration ${integration.id} from the current Hub`); + isDebugBuild() && logger.warn(`Cannot retrieve integration ${integration.id} from the current Hub`); return null; } } @@ -503,7 +511,7 @@ export class Hub implements HubInterface { if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') { return sentry.extensions[method].apply(this, args); } - logger.warn(`Extension method ${method} couldn't be found, doing nothing.`); + isDebugBuild() && logger.warn(`Extension method ${method} couldn't be found, doing nothing.`); } } @@ -566,7 +574,7 @@ export function getCurrentHub(): Hub { */ // eslint-disable-next-line deprecation/deprecation export function getActiveDomain(): DomainAsCarrier | undefined { - logger.warn('Function `getActiveDomain` is deprecated and will be removed in a future version.'); + isDebugBuild() && logger.warn('Function `getActiveDomain` is deprecated and will be removed in a future version.'); const sentry = getMainCarrier().__SENTRY__; diff --git a/packages/hub/src/sessionflusher.ts b/packages/hub/src/sessionflusher.ts index e082060689fc..fd5f82548f89 100644 --- a/packages/hub/src/sessionflusher.ts +++ b/packages/hub/src/sessionflusher.ts @@ -5,7 +5,7 @@ import { SessionFlusherLike, Transport, } from '@sentry/types'; -import { dropUndefinedKeys, logger } from '@sentry/utils'; +import { dropUndefinedKeys, isDebugBuild, logger } from '@sentry/utils'; import { getCurrentHub } from './hub'; @@ -35,11 +35,11 @@ export class SessionFlusher implements SessionFlusherLike { /** Sends session aggregates to Transport */ public sendSessionAggregates(sessionAggregates: SessionAggregates): void { if (!this._transport.sendSession) { - logger.warn("Dropping session because custom transport doesn't implement sendSession"); + isDebugBuild() && logger.warn("Dropping session because custom transport doesn't implement sendSession"); return; } void this._transport.sendSession(sessionAggregates).then(null, reason => { - logger.error('Error while sending session:', reason); + isDebugBuild() && logger.error('Error while sending session:', reason); }); } diff --git a/packages/integrations/src/angular.ts b/packages/integrations/src/angular.ts index f1e5eaccaf8c..727937d67a33 100644 --- a/packages/integrations/src/angular.ts +++ b/packages/integrations/src/angular.ts @@ -1,5 +1,5 @@ import { Event, EventProcessor, Hub, Integration } from '@sentry/types'; -import { getGlobalObject, logger } from '@sentry/utils'; +import { getGlobalObject, isDebugBuild, logger } from '@sentry/utils'; // See https://github.com/angular/angular.js/blob/v1.4.7/src/minErr.js const angularPattern = /^\[((?:[$a-zA-Z0-9]+:)?(?:[$a-zA-Z0-9]+))\] (.*?)\n?(\S+)$/; @@ -47,13 +47,13 @@ export class Angular implements Integration { */ // eslint-disable-next-line @typescript-eslint/no-explicit-any public constructor(options: { angular?: any } = {}) { - logger.log('You are still using the Angular integration, consider moving to @sentry/angular'); + isDebugBuild() && logger.log('You are still using the Angular integration, consider moving to @sentry/angular'); // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access this._angular = options.angular || getGlobalObject().angular; if (!this._angular) { - logger.error('AngularIntegration is missing an Angular instance'); + isDebugBuild() && logger.error('AngularIntegration is missing an Angular instance'); return; } diff --git a/packages/integrations/src/dedupe.ts b/packages/integrations/src/dedupe.ts index 62b6ee64427a..c6817a71ec39 100644 --- a/packages/integrations/src/dedupe.ts +++ b/packages/integrations/src/dedupe.ts @@ -1,5 +1,5 @@ import { Event, EventProcessor, Exception, Hub, Integration, StackFrame } from '@sentry/types'; -import { logger } from '@sentry/utils'; +import { isDebugBuild, logger } from '@sentry/utils'; /** Deduplication filter */ export class Dedupe implements Integration { @@ -28,7 +28,7 @@ export class Dedupe implements Integration { // Juuust in case something goes wrong try { if (_shouldDropEvent(currentEvent, self._previousEvent)) { - logger.warn('Event dropped due to being a duplicate of previously captured event.'); + isDebugBuild() && logger.warn('Event dropped due to being a duplicate of previously captured event.'); return null; } } catch (_oO) { diff --git a/packages/integrations/src/ember.ts b/packages/integrations/src/ember.ts index 811e8b4852f8..c045b8ffabcc 100644 --- a/packages/integrations/src/ember.ts +++ b/packages/integrations/src/ember.ts @@ -1,5 +1,5 @@ import { EventProcessor, Hub, Integration } from '@sentry/types'; -import { getGlobalObject, isInstanceOf, logger } from '@sentry/utils'; +import { getGlobalObject, isDebugBuild, isInstanceOf, logger } from '@sentry/utils'; /** JSDoc */ export class Ember implements Integration { @@ -33,7 +33,7 @@ export class Ember implements Integration { */ public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void { if (!this._Ember) { - logger.error('EmberIntegration is missing an Ember instance'); + isDebugBuild() && logger.error('EmberIntegration is missing an Ember instance'); return; } diff --git a/packages/integrations/src/extraerrordata.ts b/packages/integrations/src/extraerrordata.ts index ca2f13ca1542..64dcc0bad22c 100644 --- a/packages/integrations/src/extraerrordata.ts +++ b/packages/integrations/src/extraerrordata.ts @@ -1,5 +1,5 @@ import { Event, EventHint, EventProcessor, ExtendedError, Hub, Integration } from '@sentry/types'; -import { isError, isPlainObject, logger, normalize } from '@sentry/utils'; +import { isDebugBuild, isError, isPlainObject, logger, normalize } from '@sentry/utils'; /** JSDoc */ interface ExtraErrorDataOptions { @@ -120,7 +120,7 @@ export class ExtraErrorData implements Integration { return extraErrorInfo; } catch (oO) { - logger.error('Unable to extract extra data from the Error object:', oO); + isDebugBuild() && logger.error('Unable to extract extra data from the Error object:', oO); } return null; diff --git a/packages/integrations/src/offline.ts b/packages/integrations/src/offline.ts index 5cf1be2cd069..d0cc5fbb2548 100644 --- a/packages/integrations/src/offline.ts +++ b/packages/integrations/src/offline.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable @typescript-eslint/no-unsafe-member-access */ import { Event, EventProcessor, Hub, Integration } from '@sentry/types'; -import { getGlobalObject, logger, normalize, uuid4 } from '@sentry/utils'; +import { getGlobalObject, isDebugBuild, logger, normalize, uuid4 } from '@sentry/utils'; import localForage from 'localforage'; type LocalForage = { @@ -70,7 +70,7 @@ export class Offline implements Integration { if ('addEventListener' in this.global) { this.global.addEventListener('online', () => { void this._sendEvents().catch(() => { - logger.warn('could not send cached events'); + isDebugBuild() && logger.warn('could not send cached events'); }); }); } @@ -82,7 +82,7 @@ export class Offline implements Integration { void this._cacheEvent(event) .then((_event: Event): Promise => this._enforceMaxEvents()) .catch((_error): void => { - logger.warn('could not cache event while offline'); + isDebugBuild() && logger.warn('could not cache event while offline'); }); // return null on success or failure, because being offline will still result in an error @@ -96,7 +96,7 @@ export class Offline implements Integration { // if online now, send any events stored in a previous offline session if ('navigator' in this.global && 'onLine' in this.global.navigator && this.global.navigator.onLine) { void this._sendEvents().catch(() => { - logger.warn('could not send cached events'); + isDebugBuild() && logger.warn('could not send cached events'); }); } } @@ -132,7 +132,7 @@ export class Offline implements Integration { ), ) .catch((_error): void => { - logger.warn('could not enforce max events'); + isDebugBuild() && logger.warn('could not enforce max events'); }); } @@ -160,10 +160,10 @@ export class Offline implements Integration { this.hub.captureEvent(event); void this._purgeEvent(cacheKey).catch((_error): void => { - logger.warn('could not purge event from cache'); + isDebugBuild() && logger.warn('could not purge event from cache'); }); } else { - logger.warn('no hub found - could not send cached event'); + isDebugBuild() && logger.warn('no hub found - could not send cached event'); } }); } diff --git a/packages/integrations/src/vue.ts b/packages/integrations/src/vue.ts index 181593923e68..aefc8a89767b 100644 --- a/packages/integrations/src/vue.ts +++ b/packages/integrations/src/vue.ts @@ -1,7 +1,7 @@ /* eslint-disable max-lines */ /* eslint-disable @typescript-eslint/no-explicit-any */ import { EventProcessor, Hub, Integration, IntegrationClass, Scope, Span, Transaction } from '@sentry/types'; -import { basename, getGlobalObject, logger, timestampWithMs } from '@sentry/utils'; +import { basename, getGlobalObject, isDebugBuild, logger, timestampWithMs } from '@sentry/utils'; /** * Used to extract Tracing integration from the current client, @@ -156,7 +156,7 @@ export class Vue implements Integration { public constructor( options: Partial & { tracingOptions: Partial }>, ) { - logger.log('You are still using the Vue.js integration, consider moving to @sentry/vue'); + isDebugBuild() && logger.log('You are still using the Vue.js integration, consider moving to @sentry/vue'); this._options = { // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access Vue: getGlobalObject().Vue, @@ -178,7 +178,7 @@ export class Vue implements Integration { */ public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void { if (!this._options.Vue) { - logger.error('Vue integration is missing a Vue instance'); + isDebugBuild() && logger.error('Vue integration is missing a Vue instance'); return; } @@ -325,7 +325,7 @@ export class Vue implements Integration { const internalHooks = HOOKS[operation]; if (!internalHooks) { - logger.warn(`Unknown hook: ${operation}`); + isDebugBuild() && logger.warn(`Unknown hook: ${operation}`); return; } @@ -382,7 +382,8 @@ export class Vue implements Integration { // `this` points to currently rendered component applyTracingHooks(this, getCurrentHub); } else { - logger.error('Vue integration has tracing enabled, but Tracing integration is not configured'); + isDebugBuild() && + logger.error('Vue integration has tracing enabled, but Tracing integration is not configured'); } }, }); @@ -404,7 +405,7 @@ export class Vue implements Integration { metadata.propsData = vm.$options.propsData; } } catch (_oO) { - logger.warn('Unable to extract metadata from Vue component.'); + isDebugBuild() && logger.warn('Unable to extract metadata from Vue component.'); } } diff --git a/packages/nextjs/src/config/webpack.ts b/packages/nextjs/src/config/webpack.ts index 9791b2640148..0f7fd4bbd536 100644 --- a/packages/nextjs/src/config/webpack.ts +++ b/packages/nextjs/src/config/webpack.ts @@ -1,6 +1,6 @@ /* eslint-disable max-lines */ import { getSentryRelease } from '@sentry/node'; -import { dropUndefinedKeys, logger } from '@sentry/utils'; +import { dropUndefinedKeys, isDebugBuild, logger } from '@sentry/utils'; import { default as SentryWebpackPlugin } from '@sentry/webpack-plugin'; import * as fs from 'fs'; import * as os from 'os'; @@ -244,11 +244,12 @@ function checkWebpackPluginOverrides( // warn if any of the default options for the webpack plugin are getting overridden const sentryWebpackPluginOptionOverrides = Object.keys(defaultOptions).filter(key => key in userOptions); if (sentryWebpackPluginOptionOverrides.length > 0) { - logger.warn( - '[Sentry] You are overriding the following automatically-set SentryWebpackPlugin config options:\n' + - `\t${sentryWebpackPluginOptionOverrides.toString()},\n` + - "which has the possibility of breaking source map upload and application. This is only a good idea if you know what you're doing.", - ); + isDebugBuild() && + logger.warn( + '[Sentry] You are overriding the following automatically-set SentryWebpackPlugin config options:\n' + + `\t${sentryWebpackPluginOptionOverrides.toString()},\n` + + "which has the possibility of breaking source map upload and application. This is only a good idea if you know what you're doing.", + ); } } diff --git a/packages/nextjs/src/index.server.ts b/packages/nextjs/src/index.server.ts index 2d3ff2b39abe..bc2996fcfd97 100644 --- a/packages/nextjs/src/index.server.ts +++ b/packages/nextjs/src/index.server.ts @@ -3,7 +3,7 @@ import { RewriteFrames } from '@sentry/integrations'; import { configureScope, getCurrentHub, init as nodeInit, Integrations } from '@sentry/node'; import { hasTracingEnabled } from '@sentry/tracing'; import { Event } from '@sentry/types'; -import { escapeStringForRegex, logger } from '@sentry/utils'; +import { escapeStringForRegex, isDebugBuild, logger } from '@sentry/utils'; import * as domainModule from 'domain'; import * as path from 'path'; @@ -45,10 +45,10 @@ export function init(options: NextjsOptions): void { logger.enable(); } - logger.log('Initializing SDK...'); + isDebugBuild() && logger.log('Initializing SDK...'); if (sdkAlreadyInitialized()) { - logger.log('SDK already initialized'); + isDebugBuild() && logger.log('SDK already initialized'); return; } @@ -93,7 +93,7 @@ export function init(options: NextjsOptions): void { domain.active = activeDomain; } - logger.log('SDK successfully initialized'); + isDebugBuild() && logger.log('SDK successfully initialized'); } function sdkAlreadyInitialized(): boolean { @@ -150,6 +150,6 @@ if (!isVercel && !isBuild) { const { instrumentServer } = require('./utils/instrumentServer.js'); instrumentServer(); } catch (err) { - logger.warn(`Error: Unable to instrument server for tracing. Got ${err}.`); + isDebugBuild() && logger.warn(`Error: Unable to instrument server for tracing. Got ${err}.`); } } diff --git a/packages/nextjs/src/utils/instrumentServer.ts b/packages/nextjs/src/utils/instrumentServer.ts index f85089048454..fca79ac0eb45 100644 --- a/packages/nextjs/src/utils/instrumentServer.ts +++ b/packages/nextjs/src/utils/instrumentServer.ts @@ -8,7 +8,7 @@ import { startTransaction, } from '@sentry/node'; import { extractTraceparentData, getActiveTransaction, hasTracingEnabled } from '@sentry/tracing'; -import { addExceptionMechanism, fill, isString, logger, stripUrlQueryAndFragment } from '@sentry/utils'; +import { addExceptionMechanism, fill, isDebugBuild, isString, logger, stripUrlQueryAndFragment } from '@sentry/utils'; import * as domain from 'domain'; import * as http from 'http'; import { default as createNextServer } from 'next'; @@ -247,7 +247,7 @@ function makeWrappedReqHandler(origReqHandler: ReqHandler): WrappedReqHandler { let traceparentData; if (nextReq.headers && isString(nextReq.headers['sentry-trace'])) { traceparentData = extractTraceparentData(nextReq.headers['sentry-trace'] as string); - logger.log(`[Tracing] Continuing trace ${traceparentData?.traceId}.`); + isDebugBuild() && logger.log(`[Tracing] Continuing trace ${traceparentData?.traceId}.`); } // pull off query string, if any diff --git a/packages/nextjs/src/utils/withSentry.ts b/packages/nextjs/src/utils/withSentry.ts index 7781c188c3d7..bc1f1a69770c 100644 --- a/packages/nextjs/src/utils/withSentry.ts +++ b/packages/nextjs/src/utils/withSentry.ts @@ -1,7 +1,14 @@ import { captureException, flush, getCurrentHub, Handlers, startTransaction } from '@sentry/node'; import { extractTraceparentData, hasTracingEnabled } from '@sentry/tracing'; import { Transaction } from '@sentry/types'; -import { addExceptionMechanism, isString, logger, objectify, stripUrlQueryAndFragment } from '@sentry/utils'; +import { + addExceptionMechanism, + isDebugBuild, + isString, + logger, + objectify, + stripUrlQueryAndFragment, +} from '@sentry/utils'; import * as domain from 'domain'; import { NextApiHandler, NextApiRequest, NextApiResponse } from 'next'; @@ -43,7 +50,7 @@ export const withSentry = (origHandler: NextApiHandler): WrappedNextApiHandler = let traceparentData; if (req.headers && isString(req.headers['sentry-trace'])) { traceparentData = extractTraceparentData(req.headers['sentry-trace'] as string); - logger.log(`[Tracing] Continuing trace ${traceparentData?.traceId}.`); + isDebugBuild() && logger.log(`[Tracing] Continuing trace ${traceparentData?.traceId}.`); } const url = `${req.url}`; @@ -184,10 +191,10 @@ async function finishSentryProcessing(res: AugmentedNextApiResponse): Promise { public initSessionFlusher(): void { const { release, environment } = this._options; if (!release) { - logger.warn('Cannot initialise an instance of SessionFlusher if no release is provided!'); + isDebugBuild() && logger.warn('Cannot initialise an instance of SessionFlusher if no release is provided!'); } else { this._sessionFlusher = new SessionFlusher(this.getTransport(), { release, @@ -122,7 +122,7 @@ export class NodeClient extends BaseClient { */ protected _captureRequestSession(): void { if (!this._sessionFlusher) { - logger.warn('Discarded request mode session because autoSessionTracking option was disabled'); + isDebugBuild() && logger.warn('Discarded request mode session because autoSessionTracking option was disabled'); } else { this._sessionFlusher.incrementSessionStatusCount(); } diff --git a/packages/node/src/handlers.ts b/packages/node/src/handlers.ts index 4a0a431157d8..14d70cdc3453 100644 --- a/packages/node/src/handlers.ts +++ b/packages/node/src/handlers.ts @@ -4,6 +4,7 @@ import { captureException, getCurrentHub, startTransaction, withScope } from '@s import { Event, ExtractedNodeRequestData, Span, Transaction } from '@sentry/types'; import { extractTraceparentData, + isDebugBuild, isPlainObject, isString, logger, @@ -411,7 +412,7 @@ export function requestHandler( _end.call(this, chunk, encoding, cb); }) .then(null, e => { - logger.error(e); + isDebugBuild() && logger.error(e); _end.call(this, chunk, encoding, cb); }); }; diff --git a/packages/node/src/integrations/http.ts b/packages/node/src/integrations/http.ts index 9c4898cf5527..d0c820d787f7 100644 --- a/packages/node/src/integrations/http.ts +++ b/packages/node/src/integrations/http.ts @@ -1,6 +1,6 @@ import { getCurrentHub } from '@sentry/core'; import { Integration, Span } from '@sentry/types'; -import { fill, logger, parseSemver } from '@sentry/utils'; +import { fill, isDebugBuild, logger, parseSemver } from '@sentry/utils'; import * as http from 'http'; import * as https from 'https'; @@ -118,9 +118,10 @@ function _createWrappedRequestMethodFactory( }); const sentryTraceHeader = span.toTraceparent(); - logger.log( - `[Tracing] Adding sentry-trace header ${sentryTraceHeader} to outgoing request to ${requestUrl}: `, - ); + isDebugBuild() && + logger.log( + `[Tracing] Adding sentry-trace header ${sentryTraceHeader} to outgoing request to ${requestUrl}: `, + ); requestOptions.headers = { ...requestOptions.headers, 'sentry-trace': sentryTraceHeader }; } } diff --git a/packages/node/src/integrations/onuncaughtexception.ts b/packages/node/src/integrations/onuncaughtexception.ts index c5460adad25d..4fd52cba3e3f 100644 --- a/packages/node/src/integrations/onuncaughtexception.ts +++ b/packages/node/src/integrations/onuncaughtexception.ts @@ -1,6 +1,6 @@ import { getCurrentHub, Scope } from '@sentry/core'; import { Integration, Severity } from '@sentry/types'; -import { logger } from '@sentry/utils'; +import { isDebugBuild, logger } from '@sentry/utils'; import { NodeClient } from '../client'; import { logAndExitProcess } from './utils/errorhandling'; @@ -95,7 +95,8 @@ export class OnUncaughtException implements Integration { } } else if (calledFatalError) { // we hit an error *after* calling onFatalError - pretty boned at this point, just shut it down - logger.warn('uncaught exception after calling fatal error shutdown callback - this is bad! forcing shutdown'); + isDebugBuild() && + logger.warn('uncaught exception after calling fatal error shutdown callback - this is bad! forcing shutdown'); logAndExitProcess(error); } else if (!caughtSecondError) { // two cases for how we can hit this branch: diff --git a/packages/node/src/integrations/utils/errorhandling.ts b/packages/node/src/integrations/utils/errorhandling.ts index dee6809e5f55..cb1983ffb819 100644 --- a/packages/node/src/integrations/utils/errorhandling.ts +++ b/packages/node/src/integrations/utils/errorhandling.ts @@ -1,5 +1,5 @@ import { getCurrentHub } from '@sentry/core'; -import { forget, logger } from '@sentry/utils'; +import { forget, isDebugBuild, logger } from '@sentry/utils'; import { NodeClient } from '../../client'; @@ -15,7 +15,7 @@ export function logAndExitProcess(error: Error): void { const client = getCurrentHub().getClient(); if (client === undefined) { - logger.warn('No NodeClient was defined, we are exiting the process now.'); + isDebugBuild() && logger.warn('No NodeClient was defined, we are exiting the process now.'); global.process.exit(1); } @@ -26,7 +26,7 @@ export function logAndExitProcess(error: Error): void { forget( client.close(timeout).then((result: boolean) => { if (!result) { - logger.warn('We reached the timeout for emptying the request buffer, still exiting now!'); + isDebugBuild() && logger.warn('We reached the timeout for emptying the request buffer, still exiting now!'); } global.process.exit(1); }), diff --git a/packages/node/src/sdk.ts b/packages/node/src/sdk.ts index dee07c196566..201b4b073f86 100644 --- a/packages/node/src/sdk.ts +++ b/packages/node/src/sdk.ts @@ -1,7 +1,7 @@ import { getCurrentHub, initAndBind, Integrations as CoreIntegrations } from '@sentry/core'; import { getMainCarrier, setHubOnCarrier } from '@sentry/hub'; import { SessionStatus } from '@sentry/types'; -import { getGlobalObject, logger } from '@sentry/utils'; +import { getGlobalObject, isDebugBuild, logger } from '@sentry/utils'; import * as domain from 'domain'; import { NodeClient } from './client'; @@ -153,7 +153,7 @@ export async function flush(timeout?: number): Promise { if (client) { return client.flush(timeout); } - logger.warn('Cannot flush events. No client defined.'); + isDebugBuild() && logger.warn('Cannot flush events. No client defined.'); return Promise.resolve(false); } @@ -170,7 +170,7 @@ export async function close(timeout?: number): Promise { if (client) { return client.close(timeout); } - logger.warn('Cannot flush events and disable SDK. No client defined.'); + isDebugBuild() && logger.warn('Cannot flush events and disable SDK. No client defined.'); return Promise.resolve(false); } diff --git a/packages/node/src/transports/base/index.ts b/packages/node/src/transports/base/index.ts index 71ffe5783ad2..5cc15ee8fe09 100644 --- a/packages/node/src/transports/base/index.ts +++ b/packages/node/src/transports/base/index.ts @@ -12,6 +12,7 @@ import { } from '@sentry/types'; import { eventStatusFromHttpCode, + isDebugBuild, logger, makePromiseBuffer, parseRetryAfterHeader, @@ -236,11 +237,12 @@ export abstract class BaseTransport implements Transport { const limited = this._handleRateLimit(headers); if (limited) - logger.warn( - `Too many ${sentryRequest.type} requests, backing off until: ${this._disabledUntil( - sentryRequest.type, - )}`, - ); + isDebugBuild() && + logger.warn( + `Too many ${sentryRequest.type} requests, backing off until: ${this._disabledUntil( + sentryRequest.type, + )}`, + ); if (status === 'success') { resolve({ status }); diff --git a/packages/react/src/errorboundary.tsx b/packages/react/src/errorboundary.tsx index 0c73c7f9761d..6941588f794b 100644 --- a/packages/react/src/errorboundary.tsx +++ b/packages/react/src/errorboundary.tsx @@ -1,5 +1,5 @@ import { captureException, ReportDialogOptions, Scope, showReportDialog, withScope } from '@sentry/browser'; -import { logger } from '@sentry/utils'; +import { isDebugBuild, logger } from '@sentry/utils'; import hoistNonReactStatics from 'hoist-non-react-statics'; import * as React from 'react'; @@ -141,7 +141,7 @@ class ErrorBoundary extends React.Component( hub.popScope(); await flush(options.flushTimeout).catch(e => { if (options.ignoreSentryErrors && e instanceof SentryError) { - logger.error(e); + isDebugBuild() && logger.error(e); return; } throw e; diff --git a/packages/serverless/src/gcpfunction/cloud_events.ts b/packages/serverless/src/gcpfunction/cloud_events.ts index 429cea995f1a..362cb5a78563 100644 --- a/packages/serverless/src/gcpfunction/cloud_events.ts +++ b/packages/serverless/src/gcpfunction/cloud_events.ts @@ -1,5 +1,5 @@ import { captureException, flush, getCurrentHub, startTransaction } from '@sentry/node'; -import { logger } from '@sentry/utils'; +import { isDebugBuild, logger } from '@sentry/utils'; import { domainify, getActiveDomain, proxyFunction } from '../utils'; import { @@ -64,7 +64,7 @@ function _wrapCloudEventFunction( callback(...args); }) .then(null, e => { - logger.error(e); + isDebugBuild() && logger.error(e); }); }); diff --git a/packages/serverless/src/gcpfunction/events.ts b/packages/serverless/src/gcpfunction/events.ts index 6b9c7b9b14a7..f89fcbbd267f 100644 --- a/packages/serverless/src/gcpfunction/events.ts +++ b/packages/serverless/src/gcpfunction/events.ts @@ -1,5 +1,5 @@ import { captureException, flush, getCurrentHub, startTransaction } from '@sentry/node'; -import { logger } from '@sentry/utils'; +import { isDebugBuild, logger } from '@sentry/utils'; import { domainify, getActiveDomain, proxyFunction } from '../utils'; import { configureScopeWithContext, EventFunction, EventFunctionWithCallback, WrapperOptions } from './general'; @@ -59,7 +59,7 @@ function _wrapEventFunction( callback(...args); }) .then(null, e => { - logger.error(e); + isDebugBuild() && logger.error(e); }); }); diff --git a/packages/serverless/src/gcpfunction/http.ts b/packages/serverless/src/gcpfunction/http.ts index 9d50b4115643..9e9e21882d5a 100644 --- a/packages/serverless/src/gcpfunction/http.ts +++ b/packages/serverless/src/gcpfunction/http.ts @@ -1,6 +1,6 @@ import { captureException, flush, getCurrentHub, Handlers, startTransaction } from '@sentry/node'; import { extractTraceparentData } from '@sentry/tracing'; -import { isString, logger, stripUrlQueryAndFragment } from '@sentry/utils'; +import { isDebugBuild, isString, logger, stripUrlQueryAndFragment } from '@sentry/utils'; import { domainify, getActiveDomain, proxyFunction } from './../utils'; import { HttpFunction, WrapperOptions } from './general'; @@ -94,7 +94,7 @@ function _wrapHttpFunction(fn: HttpFunction, wrapOptions: Partial { - logger.error(e); + isDebugBuild() && logger.error(e); }); }; diff --git a/packages/tracing/src/browser/backgroundtab.ts b/packages/tracing/src/browser/backgroundtab.ts index 3701404b5d26..9295d83a2998 100644 --- a/packages/tracing/src/browser/backgroundtab.ts +++ b/packages/tracing/src/browser/backgroundtab.ts @@ -1,4 +1,4 @@ -import { getGlobalObject, logger } from '@sentry/utils'; +import { getGlobalObject, isDebugBuild, logger } from '@sentry/utils'; import { FINISH_REASON_TAG, IDLE_TRANSACTION_FINISH_REASONS } from '../constants'; import { IdleTransaction } from '../idletransaction'; @@ -18,9 +18,10 @@ export function registerBackgroundTabDetection(): void { if (global.document.hidden && activeTransaction) { const statusType: SpanStatusType = 'cancelled'; - logger.log( - `[Tracing] Transaction: ${statusType} -> since tab moved to the background, op: ${activeTransaction.op}`, - ); + isDebugBuild() && + logger.log( + `[Tracing] Transaction: ${statusType} -> since tab moved to the background, op: ${activeTransaction.op}`, + ); // We should not set status if it is already set, this prevent important statuses like // error or data loss from being overwritten on transaction. if (!activeTransaction.status) { @@ -32,6 +33,6 @@ export function registerBackgroundTabDetection(): void { } }); } else { - logger.warn('[Tracing] Could not set up background tab detection due to lack of global document'); + isDebugBuild() && logger.warn('[Tracing] Could not set up background tab detection due to lack of global document'); } } diff --git a/packages/tracing/src/browser/browsertracing.ts b/packages/tracing/src/browser/browsertracing.ts index 4218f8e84fd7..463d67c9d1d6 100644 --- a/packages/tracing/src/browser/browsertracing.ts +++ b/packages/tracing/src/browser/browsertracing.ts @@ -1,6 +1,6 @@ import { Hub } from '@sentry/hub'; import { EventProcessor, Integration, Transaction, TransactionContext } from '@sentry/types'; -import { getGlobalObject, logger } from '@sentry/utils'; +import { getGlobalObject, isDebugBuild, logger } from '@sentry/utils'; import { startIdleTransaction } from '../hubextensions'; import { DEFAULT_IDLE_TIMEOUT, IdleTransaction } from '../idletransaction'; @@ -160,12 +160,14 @@ export class BrowserTracing implements Integration { this._getCurrentHub = getCurrentHub; if (this._emitOptionsWarning) { - logger.warn( - '[Tracing] You need to define `tracingOrigins` in the options. Set an array of urls or patterns to trace.', - ); - logger.warn( - `[Tracing] We added a reasonable default for you: ${defaultRequestInstrumentationOptions.tracingOrigins}`, - ); + isDebugBuild() && + logger.warn( + '[Tracing] You need to define `tracingOrigins` in the options. Set an array of urls or patterns to trace.', + ); + isDebugBuild() && + logger.warn( + `[Tracing] We added a reasonable default for you: ${defaultRequestInstrumentationOptions.tracingOrigins}`, + ); } // eslint-disable-next-line @typescript-eslint/unbound-method @@ -196,7 +198,8 @@ export class BrowserTracing implements Integration { /** Create routing idle transaction. */ private _createRouteTransaction(context: TransactionContext): Transaction | undefined { if (!this._getCurrentHub) { - logger.warn(`[Tracing] Did not create ${context.op} transaction because _getCurrentHub is invalid.`); + isDebugBuild() && + logger.warn(`[Tracing] Did not create ${context.op} transaction because _getCurrentHub is invalid.`); return undefined; } @@ -217,10 +220,10 @@ export class BrowserTracing implements Integration { const finalContext = modifiedContext === undefined ? { ...expandedContext, sampled: false } : modifiedContext; if (finalContext.sampled === false) { - logger.log(`[Tracing] Will not send ${finalContext.op} transaction because of beforeNavigate.`); + isDebugBuild() && logger.log(`[Tracing] Will not send ${finalContext.op} transaction because of beforeNavigate.`); } - logger.log(`[Tracing] Starting ${finalContext.op} transaction on scope`); + isDebugBuild() && logger.log(`[Tracing] Starting ${finalContext.op} transaction on scope`); const hub = this._getCurrentHub(); const { location } = getGlobalObject() as WindowOrWorkerGlobalScope & { location: Location }; diff --git a/packages/tracing/src/browser/metrics.ts b/packages/tracing/src/browser/metrics.ts index 93253fcf2d0f..f7491a249fce 100644 --- a/packages/tracing/src/browser/metrics.ts +++ b/packages/tracing/src/browser/metrics.ts @@ -1,7 +1,14 @@ /* eslint-disable max-lines */ /* eslint-disable @typescript-eslint/no-explicit-any */ import { Measurements, SpanContext } from '@sentry/types'; -import { browserPerformanceTimeOrigin, getGlobalObject, htmlTreeAsString, isNodeEnv, logger } from '@sentry/utils'; +import { + browserPerformanceTimeOrigin, + getGlobalObject, + htmlTreeAsString, + isDebugBuild, + isNodeEnv, + logger, +} from '@sentry/utils'; import { Span } from '../span'; import { Transaction } from '../transaction'; @@ -41,7 +48,7 @@ export class MetricsInstrumentation { return; } - logger.log('[Tracing] Adding & adjusting spans using Performance API'); + isDebugBuild() && logger.log('[Tracing] Adding & adjusting spans using Performance API'); const timeOrigin = msToSec(browserPerformanceTimeOrigin); @@ -77,13 +84,13 @@ export class MetricsInstrumentation { const shouldRecord = entry.startTime < firstHidden.firstHiddenTime; if (entry.name === 'first-paint' && shouldRecord) { - logger.log('[Measurements] Adding FP'); + isDebugBuild() && logger.log('[Measurements] Adding FP'); this._measurements['fp'] = { value: entry.startTime }; this._measurements['mark.fp'] = { value: startTimestamp }; } if (entry.name === 'first-contentful-paint' && shouldRecord) { - logger.log('[Measurements] Adding FCP'); + isDebugBuild() && logger.log('[Measurements] Adding FCP'); this._measurements['fcp'] = { value: entry.startTime }; this._measurements['mark.fcp'] = { value: startTimestamp }; } @@ -113,7 +120,7 @@ export class MetricsInstrumentation { // Generate TTFB (Time to First Byte), which measured as the time between the beginning of the transaction and the // start of the response in milliseconds if (typeof responseStartTimestamp === 'number') { - logger.log('[Measurements] Adding TTFB'); + isDebugBuild() && logger.log('[Measurements] Adding TTFB'); this._measurements['ttfb'] = { value: (responseStartTimestamp - transaction.startTimestamp) * 1000 }; if (typeof requestStartTimestamp === 'number' && requestStartTimestamp <= responseStartTimestamp) { @@ -138,7 +145,8 @@ export class MetricsInstrumentation { const normalizedValue = Math.abs((measurementTimestamp - transaction.startTimestamp) * 1000); const delta = normalizedValue - oldValue; - logger.log(`[Measurements] Normalized ${name} from ${oldValue} to ${normalizedValue} (${delta})`); + isDebugBuild() && + logger.log(`[Measurements] Normalized ${name} from ${oldValue} to ${normalizedValue} (${delta})`); this._measurements[name].value = normalizedValue; }); @@ -215,7 +223,7 @@ export class MetricsInstrumentation { return; } - logger.log('[Measurements] Adding CLS'); + isDebugBuild() && logger.log('[Measurements] Adding CLS'); this._measurements['cls'] = { value: metric.value }; this._clsEntry = entry as LayoutShift; }); @@ -231,7 +239,7 @@ export class MetricsInstrumentation { const timeOrigin = msToSec(browserPerformanceTimeOrigin as number); const startTime = msToSec(entry.startTime as number); - logger.log('[Measurements] Adding LCP'); + isDebugBuild() && logger.log('[Measurements] Adding LCP'); this._measurements['lcp'] = { value: metric.value }; this._measurements['mark.lcp'] = { value: timeOrigin + startTime }; this._lcpEntry = entry as LargestContentfulPaint; @@ -248,7 +256,7 @@ export class MetricsInstrumentation { const timeOrigin = msToSec(browserPerformanceTimeOrigin as number); const startTime = msToSec(entry.startTime as number); - logger.log('[Measurements] Adding FID'); + isDebugBuild() && logger.log('[Measurements] Adding FID'); this._measurements['fid'] = { value: metric.value }; this._measurements['mark.fid'] = { value: timeOrigin + startTime }; }); @@ -401,7 +409,7 @@ function tagMetricInfo( clsEntry: MetricsInstrumentation['_clsEntry'], ): void { if (lcpEntry) { - logger.log('[Measurements] Adding LCP Data'); + isDebugBuild() && logger.log('[Measurements] Adding LCP Data'); // Capture Properties of the LCP element that contributes to the LCP. @@ -423,7 +431,7 @@ function tagMetricInfo( // See: https://developer.mozilla.org/en-US/docs/Web/API/LayoutShift if (clsEntry && clsEntry.sources) { - logger.log('[Measurements] Adding CLS Data'); + isDebugBuild() && logger.log('[Measurements] Adding CLS Data'); clsEntry.sources.forEach((source, index) => transaction.setTag(`cls.source.${index + 1}`, htmlTreeAsString(source.node)), ); diff --git a/packages/tracing/src/browser/router.ts b/packages/tracing/src/browser/router.ts index f5b5fe5f8ea3..ff1324f5709f 100644 --- a/packages/tracing/src/browser/router.ts +++ b/packages/tracing/src/browser/router.ts @@ -1,5 +1,5 @@ import { Transaction, TransactionContext } from '@sentry/types'; -import { addInstrumentationHandler, getGlobalObject, logger } from '@sentry/utils'; +import { addInstrumentationHandler, getGlobalObject, isDebugBuild, logger } from '@sentry/utils'; const global = getGlobalObject(); @@ -12,7 +12,7 @@ export function instrumentRoutingWithDefaults( startTransactionOnLocationChange: boolean = true, ): void { if (!global || !global.location) { - logger.warn('Could not initialize routing instrumentation due to invalid location'); + isDebugBuild() && logger.warn('Could not initialize routing instrumentation due to invalid location'); return; } @@ -42,7 +42,7 @@ export function instrumentRoutingWithDefaults( if (from !== to) { startingUrl = undefined; if (activeTransaction) { - logger.log(`[Tracing] Finishing current transaction with op: ${activeTransaction.op}`); + isDebugBuild() && logger.log(`[Tracing] Finishing current transaction with op: ${activeTransaction.op}`); // If there's an open transaction on the scope, we need to finish it before creating an new one. activeTransaction.finish(); } diff --git a/packages/tracing/src/errors.ts b/packages/tracing/src/errors.ts index 39537e644991..b64d0ffb85d9 100644 --- a/packages/tracing/src/errors.ts +++ b/packages/tracing/src/errors.ts @@ -1,4 +1,4 @@ -import { addInstrumentationHandler, logger } from '@sentry/utils'; +import { addInstrumentationHandler, isDebugBuild, logger } from '@sentry/utils'; import { SpanStatusType } from './span'; import { getActiveTransaction } from './utils'; @@ -18,7 +18,7 @@ function errorCallback(): void { const activeTransaction = getActiveTransaction(); if (activeTransaction) { const status: SpanStatusType = 'internal_error'; - logger.log(`[Tracing] Transaction: ${status} -> Global error occured`); + isDebugBuild() && logger.log(`[Tracing] Transaction: ${status} -> Global error occured`); activeTransaction.setStatus(status); } } diff --git a/packages/tracing/src/hubextensions.ts b/packages/tracing/src/hubextensions.ts index f4896572b6b0..85309b93cdfd 100644 --- a/packages/tracing/src/hubextensions.ts +++ b/packages/tracing/src/hubextensions.ts @@ -7,7 +7,7 @@ import { SamplingContext, TransactionContext, } from '@sentry/types'; -import { dynamicRequire, isNodeEnv, loadModule, logger } from '@sentry/utils'; +import { dynamicRequire, isDebugBuild, isNodeEnv, loadModule, logger } from '@sentry/utils'; import { registerErrorInstrumentation } from './errors'; import { IdleTransaction } from './idletransaction'; @@ -86,20 +86,21 @@ function sample(transaction: T, options: Options, samplin // Since this is coming from the user (or from a function provided by the user), who knows what we might get. (The // only valid values are booleans or numbers between 0 and 1.) if (!isValidSampleRate(sampleRate)) { - logger.warn('[Tracing] Discarding transaction because of invalid sample rate.'); + isDebugBuild() && logger.warn('[Tracing] Discarding transaction because of invalid sample rate.'); transaction.sampled = false; return transaction; } // if the function returned 0 (or false), or if `tracesSampleRate` is 0, it's a sign the transaction should be dropped if (!sampleRate) { - logger.log( - `[Tracing] Discarding transaction because ${ - typeof options.tracesSampler === 'function' - ? 'tracesSampler returned 0 or false' - : 'a negative sampling decision was inherited or tracesSampleRate is set to 0' - }`, - ); + isDebugBuild() && + logger.log( + `[Tracing] Discarding transaction because ${ + typeof options.tracesSampler === 'function' + ? 'tracesSampler returned 0 or false' + : 'a negative sampling decision was inherited or tracesSampleRate is set to 0' + }`, + ); transaction.sampled = false; return transaction; } @@ -110,15 +111,16 @@ function sample(transaction: T, options: Options, samplin // if we're not going to keep it, we're done if (!transaction.sampled) { - logger.log( - `[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number( - sampleRate, - )})`, - ); + isDebugBuild() && + logger.log( + `[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number( + sampleRate, + )})`, + ); return transaction; } - logger.log(`[Tracing] starting ${transaction.op} transaction - ${transaction.name}`); + isDebugBuild() && logger.log(`[Tracing] starting ${transaction.op} transaction - ${transaction.name}`); return transaction; } @@ -129,17 +131,19 @@ function isValidSampleRate(rate: unknown): boolean { // we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck // eslint-disable-next-line @typescript-eslint/no-explicit-any if (isNaN(rate as any) || !(typeof rate === 'number' || typeof rate === 'boolean')) { - logger.warn( - `[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify( - rate, - )} of type ${JSON.stringify(typeof rate)}.`, - ); + isDebugBuild() && + logger.warn( + `[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify( + rate, + )} of type ${JSON.stringify(typeof rate)}.`, + ); return false; } // in case sampleRate is a boolean, it will get automatically cast to 1 if it's true and 0 if it's false if (rate < 0 || rate > 1) { - logger.warn(`[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got ${rate}.`); + isDebugBuild() && + logger.warn(`[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got ${rate}.`); return false; } return true; diff --git a/packages/tracing/src/idletransaction.ts b/packages/tracing/src/idletransaction.ts index fae901ba5e20..5c3ea4fac1d6 100644 --- a/packages/tracing/src/idletransaction.ts +++ b/packages/tracing/src/idletransaction.ts @@ -1,6 +1,6 @@ import { Hub } from '@sentry/hub'; import { TransactionContext } from '@sentry/types'; -import { logger, timestampWithMs } from '@sentry/utils'; +import { isDebugBuild, logger, timestampWithMs } from '@sentry/utils'; import { FINISH_REASON_TAG, IDLE_TRANSACTION_FINISH_REASONS } from './constants'; import { Span, SpanRecorder } from './span'; @@ -92,7 +92,7 @@ export class IdleTransaction extends Transaction { // We set the transaction here on the scope so error events pick up the trace // context and attach it to the error. - logger.log(`Setting idle transaction on scope. Span ID: ${this.spanId}`); + isDebugBuild() && logger.log(`Setting idle transaction on scope. Span ID: ${this.spanId}`); _idleHub.configureScope(scope => scope.setSpan(this)); } @@ -109,7 +109,8 @@ export class IdleTransaction extends Transaction { this.activities = {}; if (this.spanRecorder) { - logger.log('[Tracing] finishing IdleTransaction', new Date(endTimestamp * 1000).toISOString(), this.op); + isDebugBuild() && + logger.log('[Tracing] finishing IdleTransaction', new Date(endTimestamp * 1000).toISOString(), this.op); for (const callback of this._beforeFinishCallbacks) { callback(this, endTimestamp); @@ -125,22 +126,24 @@ export class IdleTransaction extends Transaction { if (!span.endTimestamp) { span.endTimestamp = endTimestamp; span.setStatus('cancelled'); - logger.log('[Tracing] cancelling span since transaction ended early', JSON.stringify(span, undefined, 2)); + isDebugBuild() && + logger.log('[Tracing] cancelling span since transaction ended early', JSON.stringify(span, undefined, 2)); } const keepSpan = span.startTimestamp < endTimestamp; if (!keepSpan) { - logger.log( - '[Tracing] discarding Span since it happened after Transaction was finished', - JSON.stringify(span, undefined, 2), - ); + isDebugBuild() && + logger.log( + '[Tracing] discarding Span since it happened after Transaction was finished', + JSON.stringify(span, undefined, 2), + ); } return keepSpan; }); - logger.log('[Tracing] flushing IdleTransaction'); + isDebugBuild() && logger.log('[Tracing] flushing IdleTransaction'); } else { - logger.log('[Tracing] No active IdleTransaction'); + isDebugBuild() && logger.log('[Tracing] No active IdleTransaction'); } // if `this._onScope` is `true`, the transaction put itself on the scope when it started @@ -183,7 +186,7 @@ export class IdleTransaction extends Transaction { this.spanRecorder = new IdleTransactionSpanRecorder(pushActivity, popActivity, this.spanId, maxlen); // Start heartbeat so that transactions do not run forever. - logger.log('Starting heartbeat'); + isDebugBuild() && logger.log('Starting heartbeat'); this._pingHeartbeat(); } this.spanRecorder.add(this); @@ -198,9 +201,9 @@ export class IdleTransaction extends Transaction { clearTimeout(this._initTimeout); this._initTimeout = undefined; } - logger.log(`[Tracing] pushActivity: ${spanId}`); + isDebugBuild() && logger.log(`[Tracing] pushActivity: ${spanId}`); this.activities[spanId] = true; - logger.log('[Tracing] new activities count', Object.keys(this.activities).length); + isDebugBuild() && logger.log('[Tracing] new activities count', Object.keys(this.activities).length); } /** @@ -209,10 +212,10 @@ export class IdleTransaction extends Transaction { */ private _popActivity(spanId: string): void { if (this.activities[spanId]) { - logger.log(`[Tracing] popActivity ${spanId}`); + isDebugBuild() && logger.log(`[Tracing] popActivity ${spanId}`); // eslint-disable-next-line @typescript-eslint/no-dynamic-delete delete this.activities[spanId]; - logger.log('[Tracing] new activities count', Object.keys(this.activities).length); + isDebugBuild() && logger.log('[Tracing] new activities count', Object.keys(this.activities).length); } if (Object.keys(this.activities).length === 0) { @@ -251,7 +254,7 @@ export class IdleTransaction extends Transaction { this._prevHeartbeatString = heartbeatString; if (this._heartbeatCounter >= 3) { - logger.log('[Tracing] Transaction finished because of no change for 3 heart beats'); + isDebugBuild() && logger.log('[Tracing] Transaction finished because of no change for 3 heart beats'); this.setStatus('deadline_exceeded'); this.setTag(FINISH_REASON_TAG, IDLE_TRANSACTION_FINISH_REASONS[0]); this.finish(); @@ -264,7 +267,7 @@ export class IdleTransaction extends Transaction { * Pings the heartbeat */ private _pingHeartbeat(): void { - logger.log(`pinging Heartbeat -> current counter: ${this._heartbeatCounter}`); + isDebugBuild() && logger.log(`pinging Heartbeat -> current counter: ${this._heartbeatCounter}`); setTimeout(() => { this._beat(); }, HEARTBEAT_INTERVAL); diff --git a/packages/tracing/src/integrations/node/express.ts b/packages/tracing/src/integrations/node/express.ts index 09a9243e3c0f..35100bb615ab 100644 --- a/packages/tracing/src/integrations/node/express.ts +++ b/packages/tracing/src/integrations/node/express.ts @@ -1,5 +1,5 @@ import { Integration, Transaction } from '@sentry/types'; -import { logger } from '@sentry/utils'; +import { isDebugBuild, logger } from '@sentry/utils'; type Method = | 'all' @@ -79,7 +79,7 @@ export class Express implements Integration { */ public setupOnce(): void { if (!this._router) { - logger.error('ExpressIntegration is missing an Express instance'); + isDebugBuild() && logger.error('ExpressIntegration is missing an Express instance'); return; } instrumentMiddlewares(this._router, this._methods); diff --git a/packages/tracing/src/integrations/node/mongo.ts b/packages/tracing/src/integrations/node/mongo.ts index 806024872ea5..5a134a877bb7 100644 --- a/packages/tracing/src/integrations/node/mongo.ts +++ b/packages/tracing/src/integrations/node/mongo.ts @@ -1,6 +1,6 @@ import { Hub } from '@sentry/hub'; import { EventProcessor, Integration, SpanContext } from '@sentry/types'; -import { fill, isThenable, loadModule, logger } from '@sentry/utils'; +import { fill, isDebugBuild, isThenable, loadModule, logger } from '@sentry/utils'; // This allows us to use the same array for both defaults options and the type itself. // (note `as const` at the end to make it a union of string literal types (i.e. "a" | "b" | ... ) @@ -121,7 +121,7 @@ export class Mongo implements Integration { const pkg = loadModule<{ Collection: MongoCollection }>(moduleName); if (!pkg) { - logger.error(`Mongo Integration was unable to require \`${moduleName}\` package.`); + isDebugBuild() && logger.error(`Mongo Integration was unable to require \`${moduleName}\` package.`); return; } diff --git a/packages/tracing/src/integrations/node/mysql.ts b/packages/tracing/src/integrations/node/mysql.ts index 065a5f319175..54173fcc7a7b 100644 --- a/packages/tracing/src/integrations/node/mysql.ts +++ b/packages/tracing/src/integrations/node/mysql.ts @@ -1,6 +1,6 @@ import { Hub } from '@sentry/hub'; import { EventProcessor, Integration } from '@sentry/types'; -import { fill, loadModule, logger } from '@sentry/utils'; +import { fill, isDebugBuild, loadModule, logger } from '@sentry/utils'; interface MysqlConnection { createQuery: () => void; @@ -25,7 +25,7 @@ export class Mysql implements Integration { const pkg = loadModule('mysql/lib/Connection.js'); if (!pkg) { - logger.error('Mysql Integration was unable to require `mysql` package.'); + isDebugBuild() && logger.error('Mysql Integration was unable to require `mysql` package.'); return; } diff --git a/packages/tracing/src/integrations/node/postgres.ts b/packages/tracing/src/integrations/node/postgres.ts index eed4697147d6..880a150c0429 100644 --- a/packages/tracing/src/integrations/node/postgres.ts +++ b/packages/tracing/src/integrations/node/postgres.ts @@ -1,6 +1,6 @@ import { Hub } from '@sentry/hub'; import { EventProcessor, Integration } from '@sentry/types'; -import { fill, isThenable, loadModule, logger } from '@sentry/utils'; +import { fill, isDebugBuild, isThenable, loadModule, logger } from '@sentry/utils'; interface PgClient { prototype: { @@ -37,12 +37,12 @@ export class Postgres implements Integration { const pkg = loadModule<{ Client: PgClient; native: { Client: PgClient } }>('pg'); if (!pkg) { - logger.error('Postgres Integration was unable to require `pg` package.'); + isDebugBuild() && logger.error('Postgres Integration was unable to require `pg` package.'); return; } if (this._usePgNative && !pkg.native?.Client) { - logger.error("Postgres Integration was unable to access 'pg-native' bindings."); + isDebugBuild() && logger.error("Postgres Integration was unable to access 'pg-native' bindings."); return; } diff --git a/packages/tracing/src/transaction.ts b/packages/tracing/src/transaction.ts index bd15e1f6b8e3..e5d469d8d329 100644 --- a/packages/tracing/src/transaction.ts +++ b/packages/tracing/src/transaction.ts @@ -6,7 +6,7 @@ import { TransactionContext, TransactionMetadata, } from '@sentry/types'; -import { dropUndefinedKeys, isInstanceOf, logger } from '@sentry/utils'; +import { dropUndefinedKeys, isDebugBuild, isInstanceOf, logger } from '@sentry/utils'; import { Span as SpanClass, SpanRecorder } from './span'; @@ -92,7 +92,7 @@ export class Transaction extends SpanClass implements TransactionInterface { } if (!this.name) { - logger.warn('Transaction has no name, falling back to ``.'); + isDebugBuild() && logger.warn('Transaction has no name, falling back to ``.'); this.name = ''; } @@ -101,7 +101,7 @@ export class Transaction extends SpanClass implements TransactionInterface { if (this.sampled !== true) { // At this point if `sampled !== true` we want to discard the transaction. - logger.log('[Tracing] Discarding transaction because its trace was not chosen to be sampled.'); + isDebugBuild() && logger.log('[Tracing] Discarding transaction because its trace was not chosen to be sampled.'); const client = this._hub.getClient(); const transport = client && client.getTransport && client.getTransport(); @@ -138,11 +138,15 @@ export class Transaction extends SpanClass implements TransactionInterface { const hasMeasurements = Object.keys(this._measurements).length > 0; if (hasMeasurements) { - logger.log('[Measurements] Adding measurements to transaction', JSON.stringify(this._measurements, undefined, 2)); + isDebugBuild() && + logger.log( + '[Measurements] Adding measurements to transaction', + JSON.stringify(this._measurements, undefined, 2), + ); transaction.measurements = this._measurements; } - logger.log(`[Tracing] Finishing ${this.op} transaction: ${this.name}.`); + isDebugBuild() && logger.log(`[Tracing] Finishing ${this.op} transaction: ${this.name}.`); return this._hub.captureEvent(transaction); } diff --git a/packages/utils/src/instrument.ts b/packages/utils/src/instrument.ts index 78938468453c..985df7c09bb4 100644 --- a/packages/utils/src/instrument.ts +++ b/packages/utils/src/instrument.ts @@ -69,7 +69,8 @@ function instrument(type: InstrumentHandlerType): void { instrumentUnhandledRejection(); break; default: - logger.warn('unknown instrumentation type:', type); + isDebugBuild() && logger.warn('unknown instrumentation type:', type); + return; } } diff --git a/packages/vue/src/sdk.ts b/packages/vue/src/sdk.ts index 1877876d8561..0cccfa64fd09 100644 --- a/packages/vue/src/sdk.ts +++ b/packages/vue/src/sdk.ts @@ -1,5 +1,5 @@ import { init as browserInit, SDK_VERSION } from '@sentry/browser'; -import { getGlobalObject, logger } from '@sentry/utils'; +import { getGlobalObject, isDebugBuild, logger } from '@sentry/utils'; import { DEFAULT_HOOKS } from './constants'; import { attachErrorHandler } from './errorhandler'; @@ -41,11 +41,12 @@ export function init( browserInit(options); if (!options.Vue && !options.app) { - logger.warn( - 'Misconfigured SDK. Vue specific errors will not be captured.\n' + - 'Update your `Sentry.init` call with an appropriate config option:\n' + - '`app` (Application Instance - Vue 3) or `Vue` (Vue Constructor - Vue 2).', - ); + isDebugBuild() && + logger.warn( + 'Misconfigured SDK. Vue specific errors will not be captured.\n' + + 'Update your `Sentry.init` call with an appropriate config option:\n' + + '`app` (Application Instance - Vue 3) or `Vue` (Vue Constructor - Vue 2).', + ); return; } diff --git a/packages/vue/src/tracing.ts b/packages/vue/src/tracing.ts index 1af5db2d4777..018d3859378a 100644 --- a/packages/vue/src/tracing.ts +++ b/packages/vue/src/tracing.ts @@ -1,6 +1,6 @@ import { getCurrentHub } from '@sentry/browser'; import { Span, Transaction } from '@sentry/types'; -import { logger, timestampInSeconds } from '@sentry/utils'; +import { isDebugBuild, logger, timestampInSeconds } from '@sentry/utils'; import { formatComponentName } from './components'; import { DEFAULT_HOOKS } from './constants'; @@ -60,7 +60,7 @@ export const createTracingMixins = (options: TracingOptions): Mixins => { // eg. mount => ['beforeMount', 'mounted'] const internalHooks = HOOKS[operation]; if (!internalHooks) { - logger.warn(`Unknown hook: ${operation}`); + isDebugBuild() && logger.warn(`Unknown hook: ${operation}`); continue; } From f1863b2e44343e63997a801547ccc05a7ef416c5 Mon Sep 17 00:00:00 2001 From: Katie Byers Date: Wed, 9 Mar 2022 04:47:23 -0800 Subject: [PATCH 3/4] only enable the logger in debug bundles --- packages/core/src/sdk.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/packages/core/src/sdk.ts b/packages/core/src/sdk.ts index e6af9a5e2336..41bddfc23974 100644 --- a/packages/core/src/sdk.ts +++ b/packages/core/src/sdk.ts @@ -1,6 +1,6 @@ import { getCurrentHub } from '@sentry/hub'; import { Client, Options } from '@sentry/types'; -import { logger } from '@sentry/utils'; +import { isDebugBuild, logger } from '@sentry/utils'; /** A class object that can instantiate Client objects. */ export type ClientClass = new (options: O) => F; @@ -14,7 +14,13 @@ export type ClientClass = new (options: O) */ export function initAndBind(clientClass: ClientClass, options: O): void { if (options.debug === true) { - logger.enable(); + if (isDebugBuild()) { + logger.enable(); + } else { + // use `console.warn` rather than `logger.warn` since by non-debug bundles have all `logger.x` statements stripped + // eslint-disable-next-line no-console + console.warn('[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.'); + } } const hub = getCurrentHub(); const scope = hub.getScope(); From ea5993dd48a427a5f10699fe62a9d95c6f459304 Mon Sep 17 00:00:00 2001 From: Katie Byers Date: Wed, 9 Mar 2022 04:49:06 -0800 Subject: [PATCH 4/4] only attach the logger to __SENTRY__ in debug bundles --- packages/utils/src/logger.ts | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/packages/utils/src/logger.ts b/packages/utils/src/logger.ts index a70eaba22cdc..a6f5e41a9072 100644 --- a/packages/utils/src/logger.ts +++ b/packages/utils/src/logger.ts @@ -1,6 +1,7 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ import { WrappedFunction } from '@sentry/types'; +import { isDebugBuild } from './env'; import { getGlobalObject } from './global'; // TODO: Implement different loggers for different environments @@ -104,8 +105,13 @@ class Logger { } } -// Ensure we only have a single logger instance, even if multiple versions of @sentry/utils are being used -global.__SENTRY__ = global.__SENTRY__ || {}; -const logger = (global.__SENTRY__.logger as Logger) || (global.__SENTRY__.logger = new Logger()); +const sentryGlobal = global.__SENTRY__ || {}; +const logger = (sentryGlobal.logger as Logger) || new Logger(); + +if (isDebugBuild()) { + // Ensure we only have a single logger instance, even if multiple versions of @sentry/utils are being used + sentryGlobal.logger = logger; + global.__SENTRY__ = sentryGlobal; +} export { logger };