Skip to content

Commit aad5aa9

Browse files
committed
[v7] Make logger a property of client so it can be enabled/disabled independently
1 parent d5be7ee commit aad5aa9

File tree

35 files changed

+220
-223
lines changed

35 files changed

+220
-223
lines changed

Diff for: packages/angular/src/errorhandler.ts

+1-2
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,7 @@ class SentryErrorHandler implements AngularErrorHandler {
4343

4444
// When in development mode, log the error to console for immediate feedback.
4545
if (this._options.logErrors) {
46-
// eslint-disable-next-line no-console
47-
console.error(extractedError);
46+
console.error(extractedError); // eslint-disable-line no-console
4847
}
4948

5049
// Optionally show user dialog to provide details on what happened.

Diff for: packages/angular/src/tracing.ts

+5-4
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import { AfterViewInit, Directive, Injectable, Input, OnInit } from '@angular/core';
22
import { Event, NavigationEnd, NavigationStart, Router } from '@angular/router';
3-
import { getTransaction } from '@sentry/minimal';
3+
import { getCurrentClient, getTransaction } from '@sentry/minimal';
44
import { Span, Transaction, TransactionContext } from '@sentry/types';
5-
import { logger, stripUrlQueryAndFragment, timestampWithMs } from '@sentry/utils';
5+
import { stripUrlQueryAndFragment, timestampWithMs } from '@sentry/utils';
66
import { Observable } from 'rxjs';
77
import { filter, tap } from 'rxjs/operators';
88

@@ -39,14 +39,15 @@ export class TraceService {
3939
public navStart$: Observable<Event> = this._router.events.pipe(
4040
filter(event => event instanceof NavigationStart),
4141
tap(event => {
42+
const client = getCurrentClient();
4243
if (!instrumentationInitialized) {
43-
logger.error('Angular integration has tracing enabled, but Tracing integration is not configured');
44+
client?.logger.error('Angular integration has tracing enabled, but Tracing integration is not configured');
4445
return;
4546
}
4647

4748
const navigationEvent = event as NavigationStart;
4849
const strippedUrl = stripUrlQueryAndFragment(navigationEvent.url);
49-
let activeTransaction = getTransaction();
50+
let activeTransaction = client?.getScope().getTransaction();
5051

5152
if (!activeTransaction && stashedStartTransactionOnLocationChange) {
5253
activeTransaction = stashedStartTransaction({

Diff for: packages/browser/src/sdk.ts

+6-6
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { ClientLike, Integration } from '@sentry/types';
22
import { captureException, getCarrier, getCurrentClient } from '@sentry/minimal';
3-
import { addInstrumentationHandler, getGlobalObject, logger, supportsFetch } from '@sentry/utils';
3+
import { addInstrumentationHandler, getGlobalObject, supportsFetch } from '@sentry/utils';
44
import { Dsn, getReportDialogEndpoint, ReportDialogOptions } from '@sentry/transport-base';
55
import { InboundFilters } from '@sentry/integration-common-inboundfilters';
66
import { UserAgent } from '@sentry/integration-browser-useragent';
@@ -99,17 +99,17 @@ export function showReportDialog(
9999
options.dsn = options.dsn ?? client.options.dsn;
100100

101101
if (client.options.enabled === false) {
102-
logger.error(`${errPrefix} disabled client`);
102+
client.logger.error(`${errPrefix} disabled client`);
103103
return;
104104
}
105105

106106
if (!options.eventId) {
107-
logger.error(`${errPrefix} missing EventID`);
107+
client.logger.error(`${errPrefix} missing EventID`);
108108
return;
109109
}
110110

111111
if (!options.dsn) {
112-
logger.error(`${errPrefix} missing DSN`);
112+
client.logger.error(`${errPrefix} missing DSN`);
113113
return;
114114
}
115115

@@ -161,12 +161,12 @@ export function wrap(fn: (...args: unknown[]) => unknown): unknown {
161161
/**
162162
* Enable automatic Session Tracking for the initial page load.
163163
*/
164-
function startSessionTracking(_client: ClientLike): void {
164+
function startSessionTracking(client: ClientLike): void {
165165
const window = getGlobalObject<Window>();
166166
const document = window.document;
167167

168168
if (typeof document === 'undefined') {
169-
logger.warn('Session tracking in non-browser environment with @sentry/browser is not supported.');
169+
client.logger.warn('Session tracking in non-browser environment with @sentry/browser is not supported.');
170170
return;
171171
}
172172

Diff for: packages/core/src/baseclient.ts

+22-15
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,9 @@ import {
1212
import {
1313
dateTimestampInSeconds,
1414
getEventDescription,
15+
Logger,
1516
isPlainObject,
1617
isPrimitive,
17-
logger,
1818
normalize,
1919
truncate,
2020
uuid4,
@@ -67,6 +67,9 @@ export abstract class BaseClient<O extends Options> implements ClientLike<O> {
6767
/** Options passed to the SDK. */
6868
public readonly options: O;
6969

70+
/** Logger used for debug mode */
71+
public readonly logger = new Logger('Client');
72+
7073
/** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */
7174
public readonly dsn?: Dsn;
7275

@@ -88,10 +91,14 @@ export abstract class BaseClient<O extends Options> implements ClientLike<O> {
8891
* @param options Options for the client.
8992
*/
9093
protected constructor(options: O) {
91-
this.options = options;
94+
this.options = options ?? {};
95+
96+
if (this.options.dsn) {
97+
this.dsn = new Dsn(this.options.dsn);
98+
}
9299

93-
if (options.dsn) {
94-
this.dsn = new Dsn(options.dsn);
100+
if (this.options.debug) {
101+
this.logger.enabled = true;
95102
}
96103

97104
this._transport = this._setupTransport();
@@ -155,7 +162,7 @@ export abstract class BaseClient<O extends Options> implements ClientLike<O> {
155162
*/
156163
public captureSession(session: Session): void {
157164
if (!session.release) {
158-
logger.warn('Discarded session because of missing release');
165+
this.logger.warn('Discarded session because of missing release');
159166
} else {
160167
this._sendSession(session);
161168
// After sending, we set init false to inidcate it's not the first occurence
@@ -206,7 +213,7 @@ export abstract class BaseClient<O extends Options> implements ClientLike<O> {
206213
return integrations.reduce((integrationsIndex: Record<string, Integration>, integration) => {
207214
integrationsIndex[integration.name] = integration;
208215
integration.install(this);
209-
logger.log(`Integration installed: ${integration.name}`);
216+
this.logger.log(`Integration installed: ${integration.name}`);
210217
return integrationsIndex;
211218
}, {});
212219
}
@@ -217,7 +224,7 @@ export abstract class BaseClient<O extends Options> implements ClientLike<O> {
217224
// TODO: Do we need generic here?
218225
protected _sendRequest<T>(request: TransportRequest<T>): void {
219226
this._transport.sendRequest(request).then(null, reason => {
220-
logger.error(`Failed sending request: ${reason}`);
227+
this.logger.error(`Failed sending request: ${reason}`);
221228
});
222229
}
223230

@@ -431,7 +438,7 @@ export abstract class BaseClient<O extends Options> implements ClientLike<O> {
431438
// eslint-disable-next-line complexity
432439
protected _processEvent(event: SentryEvent, captureContext: CaptureContext): SentryEvent | null {
433440
if (this.options.enabled === false) {
434-
logger.error('SDK not enabled, will not send event.');
441+
this.logger.error('SDK not enabled, will not send event.');
435442
return null;
436443
}
437444

@@ -440,7 +447,7 @@ export abstract class BaseClient<O extends Options> implements ClientLike<O> {
440447
// 0.0 === 0% events are sent
441448
// Sampling for transaction happens somewhere else
442449
if (!isTransaction && typeof this.options.sampleRate === 'number' && Math.random() > this.options.sampleRate) {
443-
logger.error(
450+
this.logger.error(
444451
`Discarding event because it's not included in the random sample (sampling rate = ${this.options.sampleRate})`,
445452
);
446453
return null;
@@ -466,23 +473,23 @@ export abstract class BaseClient<O extends Options> implements ClientLike<O> {
466473

467474
processedEvent = scope.applyToEvent(processedEvent, captureContext.hint);
468475
if (processedEvent === null) {
469-
logger.error('A scope event processor returned null, will not send event.');
476+
this.logger.error('A scope event processor returned null, will not send event.');
470477
return null;
471478
}
472479

473480
for (const processor of this._eventProcessors) {
474481
if (typeof processor === 'function') {
475482
const nextEvent = processor(processedEvent, captureContext.hint);
476483
if (nextEvent === null) {
477-
logger.error('A client event processor returned null, will not send event.');
484+
this.logger.error('A client event processor returned null, will not send event.');
478485
return null;
479486
}
480487
processedEvent = nextEvent;
481488
}
482489
}
483490

484491
if (processedEvent === null) {
485-
logger.error('A scope event processor returned null, will not send event.');
492+
this.logger.error('A scope event processor returned null, will not send event.');
486493
return null;
487494
}
488495

@@ -499,12 +506,12 @@ export abstract class BaseClient<O extends Options> implements ClientLike<O> {
499506
processedEvent = this.options.beforeSend(processedEvent as SentryEvent, captureContext?.hint);
500507

501508
if (!(isPlainObject(processedEvent) || processedEvent === null)) {
502-
logger.error('`beforeSend` method has to return `null` or a valid event.');
509+
this.logger.error('`beforeSend` method has to return `null` or a valid event.');
503510
return null;
504511
}
505512

506513
if (processedEvent === null) {
507-
logger.error('`beforeSend` returned `null`, will not send event.');
514+
this.logger.error('`beforeSend` returned `null`, will not send event.');
508515
return null;
509516
}
510517

@@ -525,7 +532,7 @@ export abstract class BaseClient<O extends Options> implements ClientLike<O> {
525532
originalException: e,
526533
},
527534
});
528-
logger.error(
535+
this.logger.error(
529536
`Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: ${e}`,
530537
);
531538
return null;

Diff for: packages/integration-browser-globalhandlers/src/onerror.ts

+1-2
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import {
77
isErrorEvent,
88
isPrimitive,
99
isString,
10-
logger,
1110
} from '@sentry/utils';
1211
import { eventFromUnknownInput } from '@sentry/eventbuilder-browser';
1312

@@ -45,7 +44,7 @@ export class OnError implements Integration {
4544
type: 'error',
4645
});
4746

48-
logger.log('Global Handler attached: onerror');
47+
client.logger.log('Global Handler attached: onerror');
4948
}
5049

5150
/**

Diff for: packages/integration-browser-globalhandlers/src/onunhandledrejection.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
22
import { ClientLike, SentryEvent, Integration, Primitive, Severity } from '@sentry/types';
3-
import { addExceptionMechanism, addInstrumentationHandler, isPrimitive, logger } from '@sentry/utils';
3+
import { addExceptionMechanism, addInstrumentationHandler, isPrimitive } from '@sentry/utils';
44
import { eventFromUnknownInput } from '@sentry/eventbuilder-browser';
55

66
export class OnUnhandledRejection implements Integration {
@@ -60,7 +60,7 @@ export class OnUnhandledRejection implements Integration {
6060
type: 'unhandledrejection',
6161
});
6262

63-
logger.log('Global Handler attached: onunhandledrejection');
63+
client.logger.log('Global Handler attached: onunhandledrejection');
6464
}
6565

6666
/**

Diff for: packages/integration-browser-offline/src/index.ts

+7-11
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import { SentryEvent, ClientLike, Integration } from '@sentry/types';
2-
import { getGlobalObject, logger, normalize, uuid4 } from '@sentry/utils';
3-
2+
import { getGlobalObject, normalize, uuid4 } from '@sentry/utils';
43
import * as localForageType from 'localforage';
54

65
// eslint-disable-next-line @typescript-eslint/no-var-requires
@@ -16,8 +15,7 @@ export class Offline implements Integration {
1615
/**
1716
* the global instance
1817
*/
19-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
20-
public global: any;
18+
public global = getGlobalObject<Window>();
2119

2220
/**
2321
* maximum number of events to store while offline
@@ -35,8 +33,6 @@ export class Offline implements Integration {
3533
* @inheritDoc
3634
*/
3735
public constructor(options: OfflineOptions = {}) {
38-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
39-
this.global = getGlobalObject<any>();
4036
this.maxStoredEvents = options.maxStoredEvents ?? 30; // set a reasonable default
4137
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
4238
this.offlineEventStore = localForage.createInstance({
@@ -53,7 +49,7 @@ export class Offline implements Integration {
5349
if ('addEventListener' in this.global) {
5450
this.global.addEventListener('online', () => {
5551
this._sendEvents().catch(() => {
56-
logger.warn('could not send cached events');
52+
this._client.logger.warn('could not send cached events');
5753
});
5854
});
5955
}
@@ -64,7 +60,7 @@ export class Offline implements Integration {
6460
this._cacheEvent(event)
6561
.then((_event: SentryEvent): Promise<void> => this._enforceMaxEvents())
6662
.catch((_error): void => {
67-
logger.warn('could not cache event while offline');
63+
this._client.logger.warn('could not cache event while offline');
6864
});
6965

7066
// return null on success or failure, because being offline will still result in an error
@@ -77,7 +73,7 @@ export class Offline implements Integration {
7773
// if online now, send any events stored in a previous offline session
7874
if ('navigator' in this.global && 'onLine' in this.global.navigator && this.global.navigator.onLine) {
7975
this._sendEvents().catch(() => {
80-
logger.warn('could not send cached events');
76+
this._client.logger.warn('could not send cached events');
8177
});
8278
}
8379
}
@@ -113,7 +109,7 @@ export class Offline implements Integration {
113109
),
114110
)
115111
.catch((_error): void => {
116-
logger.warn('could not enforce max events');
112+
this._client.logger.warn('could not enforce max events');
117113
});
118114
}
119115

@@ -141,7 +137,7 @@ export class Offline implements Integration {
141137
this._client.captureEvent(event);
142138

143139
this._purgeEvent(cacheKey).catch((_error): void => {
144-
logger.warn('could not purge event from cache');
140+
this._client.logger.warn('could not purge event from cache');
145141
});
146142
},
147143
);

Diff for: packages/integration-common-extraerrordata/src/index.ts

+5-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { SentryEvent, EventHint, ExtendedError, ClientLike, Integration } from '@sentry/types';
2-
import { isError, isPlainObject, logger, normalize } from '@sentry/utils';
2+
import { isError, isPlainObject, normalize } from '@sentry/utils';
33

44
interface ExtraErrorDataOptions {
55
depth?: number;
@@ -8,12 +8,15 @@ interface ExtraErrorDataOptions {
88
export class ExtraErrorData implements Integration {
99
public name = this.constructor.name;
1010

11+
private _client!: ClientLike;
12+
1113
public constructor(private readonly _options: ExtraErrorDataOptions = { depth: 3 }) {}
1214

1315
/**
1416
* @inheritDoc
1517
*/
1618
public install(client: ClientLike): void {
19+
this._client = client;
1720
client.addEventProcessor((event: SentryEvent, hint?: EventHint) => this.enhanceEventWithErrorData(event, hint));
1821
}
1922

@@ -75,7 +78,7 @@ export class ExtraErrorData implements Integration {
7578
result = extraErrorInfo;
7679
}
7780
} catch (oO) {
78-
logger.error('Unable to extract extra data from the Error object:', oO);
81+
this._client.logger.error('Unable to extract extra data from the Error object:', oO);
7982
}
8083

8184
return result;

0 commit comments

Comments
 (0)