Skip to content

Commit 0b2876c

Browse files
committed
fix(many): gate debug logs behind the DEBUG log level
1 parent 279fb16 commit 0b2876c

14 files changed

Lines changed: 288 additions & 96 deletions

File tree

‎core/src/utils/config.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,7 @@ export interface IonicConfig {
217217
* - `'OFF'`: No errors or warnings are logged.
218218
* - `'ERROR'`: Logs only errors.
219219
* - `'WARN'`: Logs errors and warnings.
220+
* - `'DEBUG'`: Logs errors, warnings, and Ionic's internal diagnostics.
220221
*/
221222
logLevel?: LogLevel;
222223

‎core/src/utils/logging/index.ts‎

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,34 @@ export enum LogLevel {
44
OFF = 'OFF',
55
ERROR = 'ERROR',
66
WARN = 'WARN',
7+
DEBUG = 'DEBUG',
78
}
89

10+
/** Each level logs everything below it. */
11+
const LOG_LEVEL_RANK: Record<LogLevel, number> = {
12+
[LogLevel.OFF]: 0,
13+
[LogLevel.ERROR]: 1,
14+
[LogLevel.WARN]: 2,
15+
[LogLevel.DEBUG]: 3,
16+
};
17+
18+
/**
19+
* Whether the configured level is verbose enough to log `minimum`. Levels set
20+
* through a query parameter arrive as raw strings, hence the uppercasing.
21+
*/
22+
const isLogLevelEnabled = (minimum: LogLevel): boolean => {
23+
const configured = String(config.get('logLevel', LogLevel.WARN)).toUpperCase() as LogLevel;
24+
return LOG_LEVEL_RANK[configured] >= LOG_LEVEL_RANK[minimum];
25+
};
26+
927
/**
1028
* Logs a warning to the console with an Ionic prefix
1129
* to indicate the library that is warning the developer.
1230
*
1331
* @param message - The string message to be logged to the console.
1432
*/
1533
export const printIonWarning = (message: string, ...params: any[]) => {
16-
const logLevel = config.get('logLevel', LogLevel.WARN);
17-
if ([LogLevel.WARN].includes(logLevel)) {
34+
if (isLogLevelEnabled(LogLevel.WARN)) {
1835
return console.warn(`[Ionic Warning]: ${message}`, ...params);
1936
}
2037
};
@@ -27,8 +44,7 @@ export const printIonWarning = (message: string, ...params: any[]) => {
2744
* @param params - Additional arguments to supply to the console.error.
2845
*/
2946
export const printIonError = (message: string, ...params: any[]) => {
30-
const logLevel = config.get('logLevel', LogLevel.ERROR);
31-
if ([LogLevel.ERROR, LogLevel.WARN].includes(logLevel)) {
47+
if (isLogLevelEnabled(LogLevel.ERROR)) {
3248
return console.error(`[Ionic Error]: ${message}`, ...params);
3349
}
3450
};

‎core/src/utils/logging/test/logging.spec.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,16 @@ describe('Logging', () => {
3737
});
3838
});
3939

40+
describe("when the logLevel configuration is set to 'DEBUG'", () => {
41+
it('logs a warning to the console', () => {
42+
config.set('logLevel', LogLevel.DEBUG);
43+
44+
printIonWarning('This is a warning message');
45+
46+
expect(consoleWarnSpy).toHaveBeenCalledWith('[Ionic Warning]: This is a warning message');
47+
});
48+
});
49+
4050
describe("when the logLevel configuration is set to 'ERROR'", () => {
4151
it('does not log a warning to the console', () => {
4252
config.set('logLevel', LogLevel.ERROR);
@@ -101,6 +111,16 @@ describe('Logging', () => {
101111
});
102112
});
103113

114+
describe("when the logLevel configuration is set to 'DEBUG'", () => {
115+
it('logs an error to the console', () => {
116+
config.set('logLevel', LogLevel.DEBUG);
117+
118+
printIonError('This is an error message');
119+
120+
expect(consoleErrorSpy).toHaveBeenCalledWith('[Ionic Error]: This is an error message');
121+
});
122+
});
123+
104124
describe("when the logLevel configuration is set to 'OFF'", () => {
105125
it('does not log an error to the console', () => {
106126
config.set('logLevel', LogLevel.OFF);

‎docs/react-router/README.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,21 @@ See our [Contributing Guide](/docs/CONTRIBUTING.md).
99
## Testing
1010

1111
Refer to the [React Router Testing documentation](./testing.md) for testing the React Router package.
12+
13+
## Debug Logging
14+
15+
The `StackManager` logs the decisions behind the swipe-to-go-back gesture: whether it can start, which views are entering and leaving, and whether the entering page ends up visible. These logs are off in every build, dev included. Ionic's `logLevel` config turns them on, either through the URL:
16+
17+
```
18+
http://localhost:3000/routing?ionic:logLevel=DEBUG
19+
```
20+
21+
or before the app renders:
22+
23+
```tsx
24+
import { LogLevel, setupIonicReact } from '@ionic/react';
25+
26+
setupIonicReact({ logLevel: LogLevel.DEBUG });
27+
```
28+
29+
See [the testing docs](./testing.md#debug-logging-in-e2e-runs) for how to read them in a failing e2e run.

‎docs/react-router/testing.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,15 @@ Useful flags:
4242
| `--app <name>` | Pick a different app variant from `packages/react-router/test/apps/` (default: `reactrouter6-react18`; use `reactrouter6-react19` for the latest supported React version) |
4343
| `--serve` | Start the dev server only and open the browser |
4444

45+
## Debug Logging in E2E Runs
46+
47+
The test app starts with `setupIonicReact({ logLevel: LogLevel.DEBUG })`, so the `StackManager` swipe-back diagnostics are on for every spec.
48+
49+
- Cypress prints the browser console to the terminal on failure, via `cypress-terminal-report`.
50+
- Playwright records a trace on the first retry, so CI failures come with one. Open it with `npx playwright show-trace <path>` and read the console tab. Retries are off locally, so pass `--trace on` when you want the same thing from a local run. Don't turn tracing on by default: the recording overhead is enough to destabilize the tab lifecycle specs on React 19.
51+
52+
A passing run collects the same logs in the browser and throws them away, so nothing reaches your terminal. See [Debug Logging](./README.md#debug-logging) for turning them on in your own app.
53+
4554
## Test App Build Structure
4655

4756
Unlike other test applications, these test apps are broken up into multiple directories. These directories are then combined to create a single application. This allows us to share common application code, tests, etc so that each app is being tested the same way. Below details the different pieces that help create a single test application.

‎packages/react-router/src/ReactRouter/StackManager.tsx‎

Lines changed: 32 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
*/
66

77
import type { RouteInfo, StackContextState, ViewItem } from '@ionic/react';
8-
import { IonRoute, RouteManagerContext, StackContext, generateId } from '@ionic/react';
8+
import { IonRoute, RouteManagerContext, StackContext, createDebugLogger, generateId } from '@ionic/react';
99
import React from 'react';
1010
import type { RouteObject } from 'react-router-dom';
1111
import { Route, UNSAFE_RouteContext as RouteContext, matchRoutes } from 'react-router-dom';
@@ -35,6 +35,9 @@ const VIEW_UNMOUNT_DELAY_MS = 250;
3535
*/
3636
const ION_PAGE_WAIT_TIMEOUT_MS = 300;
3737

38+
/** Off unless the app sets `logLevel: 'DEBUG'`. */
39+
const debug = createDebugLogger('react-router');
40+
3841
interface StackManagerProps {
3942
routeInfo: RouteInfo;
4043
id?: string;
@@ -47,19 +50,6 @@ const isViewVisible = (el: HTMLElement) =>
4750

4851
const hideIonPageElement = (element: HTMLElement | undefined): void => {
4952
if (element) {
50-
if (element.id === 'section-a' || element.id === 'section-b') {
51-
// eslint-disable-next-line no-console
52-
console.log(
53-
'[HideIonPageElement]',
54-
JSON.stringify({
55-
id: element.id,
56-
stack: new Error().stack
57-
?.split('\n')
58-
.slice(1, 6)
59-
.map((s) => s.trim()),
60-
})
61-
);
62-
}
6353
element.classList.add('ion-page-hidden');
6454
element.setAttribute('aria-hidden', 'true');
6555
}
@@ -91,32 +81,9 @@ const showIonPageElement = (element: HTMLElement | undefined): void => {
9181
*/
9282
const revealIonPageForSwipeBack = (element: HTMLElement | undefined): void => {
9383
if (element) {
94-
const before = {
95-
id: element.id,
96-
inlineDisplay: element.style.display,
97-
hasHiddenClass: element.classList.contains('ion-page-hidden'),
98-
ariaHidden: element.getAttribute('aria-hidden'),
99-
computedDisplay: getComputedStyle(element).display,
100-
};
10184
element.style.removeProperty('display');
10285
element.classList.remove('ion-page-hidden');
10386
element.removeAttribute('aria-hidden');
104-
// eslint-disable-next-line no-console
105-
console.log(
106-
'[SwipeBackReveal]',
107-
JSON.stringify({
108-
before,
109-
after: {
110-
inlineDisplay: element.style.display,
111-
hasHiddenClass: element.classList.contains('ion-page-hidden'),
112-
ariaHidden: element.getAttribute('aria-hidden'),
113-
computedDisplay: getComputedStyle(element).display,
114-
},
115-
})
116-
);
117-
} else {
118-
// eslint-disable-next-line no-console
119-
console.log('[SwipeBackReveal] element is undefined');
12087
}
12188
};
12289

@@ -1433,20 +1400,16 @@ export class StackManager extends React.PureComponent<StackManagerProps> {
14331400
enteringViewItem.routeData.match.pattern.path !== routeInfo.pathname &&
14341401
enteringViewItem.routeData.match.pathname !== routeInfo.pathname;
14351402

1436-
// eslint-disable-next-line no-console
1437-
console.log(
1438-
'[SwipeBackCanStart]',
1439-
JSON.stringify({
1440-
outletId: this.id,
1441-
routePathname: routeInfo.pathname,
1442-
swipeBackPathname: swipeBackRouteInfo?.pathname,
1443-
enteringViewId: enteringViewItem?.id,
1444-
enteringViewPath: enteringViewItem?.reactElement?.props?.path,
1445-
enteringMount: enteringViewItem?.mount,
1446-
ionPageInDocument,
1447-
canStartSwipe,
1448-
})
1449-
);
1403+
debug('SwipeBackCanStart', () => ({
1404+
outletId: this.id,
1405+
routePathname: routeInfo.pathname,
1406+
swipeBackPathname: swipeBackRouteInfo?.pathname,
1407+
enteringViewId: enteringViewItem?.id,
1408+
enteringViewPath: enteringViewItem?.reactElement?.props?.path,
1409+
enteringMount: enteringViewItem?.mount,
1410+
ionPageInDocument,
1411+
canStartSwipe,
1412+
}));
14501413

14511414
return canStartSwipe;
14521415
};
@@ -1457,20 +1420,16 @@ export class StackManager extends React.PureComponent<StackManagerProps> {
14571420
const enteringViewItem = this.findEnteringViewForSwipe(swipeBackRouteInfo);
14581421
const leavingViewItem = this.context.findViewItemByRouteInfo(routeInfo, this.id, false);
14591422

1460-
// eslint-disable-next-line no-console
1461-
console.log(
1462-
'[SwipeBackOnStart:entry]',
1463-
JSON.stringify({
1464-
outletId: this.id,
1465-
routePathname: routeInfo.pathname,
1466-
swipeBackPathname: swipeBackRouteInfo?.pathname,
1467-
enteringViewId: enteringViewItem?.id,
1468-
enteringViewPath: enteringViewItem?.reactElement?.props?.path,
1469-
enteringMount: enteringViewItem?.mount,
1470-
hasEnteringIonPageElement: !!enteringViewItem?.ionPageElement,
1471-
leavingViewId: leavingViewItem?.id,
1472-
})
1473-
);
1423+
debug('SwipeBackOnStart:entry', () => ({
1424+
outletId: this.id,
1425+
routePathname: routeInfo.pathname,
1426+
swipeBackPathname: swipeBackRouteInfo?.pathname,
1427+
enteringViewId: enteringViewItem?.id,
1428+
enteringViewPath: enteringViewItem?.reactElement?.props?.path,
1429+
enteringMount: enteringViewItem?.mount,
1430+
hasEnteringIonPageElement: !!enteringViewItem?.ionPageElement,
1431+
leavingViewId: leavingViewItem?.id,
1432+
}));
14741433

14751434
// Ensure the entering view is mounted so React keeps rendering it during the gesture.
14761435
// This is important when the view was previously marked for unmount but its
@@ -1489,18 +1448,14 @@ export class StackManager extends React.PureComponent<StackManagerProps> {
14891448
await this.transitionPage(routeInfo, enteringViewItem, leavingViewItem, 'back', true);
14901449
}
14911450

1492-
// eslint-disable-next-line no-console
1493-
console.log(
1494-
'[SwipeBackOnStart:exit]',
1495-
JSON.stringify({
1496-
outletId: this.id,
1497-
enteringFinalComputedDisplay: enteringViewItem?.ionPageElement
1498-
? getComputedStyle(enteringViewItem.ionPageElement).display
1499-
: null,
1500-
enteringFinalInlineDisplay: enteringViewItem?.ionPageElement?.style.display ?? null,
1501-
enteringFinalHiddenClass: enteringViewItem?.ionPageElement?.classList.contains('ion-page-hidden') ?? null,
1502-
})
1503-
);
1451+
debug('SwipeBackOnStart:exit', () => ({
1452+
outletId: this.id,
1453+
enteringFinalComputedDisplay: enteringViewItem?.ionPageElement
1454+
? getComputedStyle(enteringViewItem.ionPageElement).display
1455+
: null,
1456+
enteringFinalInlineDisplay: enteringViewItem?.ionPageElement?.style.display ?? null,
1457+
enteringFinalHiddenClass: enteringViewItem?.ionPageElement?.classList.contains('ion-page-hidden') ?? null,
1458+
}));
15041459

15051460
return Promise.resolve();
15061461
};

‎packages/react-router/test/base/src/App.tsx‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { IonApp, setupIonicReact, IonRouterOutlet } from '@ionic/react';
1+
import { IonApp, setupIonicReact, LogLevel, IonRouterOutlet } from '@ionic/react';
22
import React from 'react';
33
import { Route, Navigate } from 'react-router-dom';
44

@@ -72,7 +72,8 @@ import SuspenseOutlet from './pages/suspense-outlet/SuspenseOutlet';
7272
import { PropsUpdateDirect, PropsUpdateRoutesWrapper } from './pages/props-update/PropsUpdate';
7373
import DisabledButton from './pages/disabled-button/DisabledButton';
7474

75-
setupIonicReact();
75+
// Debug logs on so failing specs include the navigation diagnostics.
76+
setupIonicReact({ logLevel: LogLevel.DEBUG });
7677

7778
const App: React.FC = () => {
7879
return (

‎packages/react/src/components/IonIcon.tsx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
import React from 'react';
22

33
import { NavContext } from '../contexts/NavContext';
4+
import { getConfig } from '../utils/config';
45

56
import type { IonicReactProps } from './IonicReactProps';
67
import { IonIconInner } from './inner-proxies';
7-
import { createForwardRef, getConfig } from './utils';
8+
import { createForwardRef } from './utils';
89

910
interface IonIconProps {
1011
color?: string;

‎packages/react/src/components/index.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ export {
1111
getTimeGivenProgression,
1212
getIonPageElement,
1313
openURL,
14+
LogLevel,
1415

1516
// TYPES
1617
Animation,
@@ -124,7 +125,8 @@ export * from './IonRoute';
124125
export * from './IonRouterContext';
125126

126127
// Utils
127-
export { isPlatform, getPlatforms, getConfig } from './utils';
128+
export { isPlatform, getPlatforms } from './utils';
129+
export { getConfig } from '../utils/config';
128130
export * from './hrefprops';
129131

130132
// Ionic Animations

‎packages/react/src/components/utils/index.tsx‎

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { Config as CoreConfig, Platforms } from '@ionic/core/components';
1+
import type { Platforms } from '@ionic/core/components';
22
import { getPlatforms as getPlatformsCore, isPlatform as isPlatformCore } from '@ionic/core/components';
33
import React from 'react';
44

@@ -39,13 +39,3 @@ export const isPlatform = (platform: Platforms) => {
3939
export const getPlatforms = () => {
4040
return getPlatformsCore(window);
4141
};
42-
43-
export const getConfig = (): CoreConfig | null => {
44-
if (typeof (window as any) !== 'undefined') {
45-
const Ionic = (window as any).Ionic;
46-
if (Ionic && Ionic.config) {
47-
return Ionic.config;
48-
}
49-
}
50-
return null;
51-
};

0 commit comments

Comments
 (0)