Skip to content

Commit 866ebd4

Browse files
committed
Add setLogLevel
1 parent c87c994 commit 866ebd4

File tree

11 files changed

+98
-36
lines changed

11 files changed

+98
-36
lines changed

src/CodePush.tsx

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import hoistStatics from 'hoist-non-react-statics';
22
import React from 'react';
33
import { AppState } from 'react-native';
44
import { CheckFrequency } from './enums/CheckFrequency.enum';
5+
import { LogLevel } from './enums/LogLevel.enum';
6+
import { log } from './internals/utils/log';
57
import { notifyAppReady } from './notifyAppReady';
68
import { sync } from './sync';
79
import type {
@@ -54,6 +56,8 @@ export function withCodePush<P extends object>(optionsOrComponent: CodePushOptio
5456
}
5557

5658
componentDidMount() {
59+
log(LogLevel.DEBUG, `withCodePush ${JSON.stringify(options)}`);
60+
5761
if (options.checkFrequency === CheckFrequency.MANUAL) {
5862
notifyAppReady();
5963
} else {
@@ -75,11 +79,13 @@ export function withCodePush<P extends object>(optionsOrComponent: CodePushOptio
7579
rootComponentInstance.codePushOnBinaryVersionMismatch.bind(rootComponentInstance);
7680
}
7781

82+
log(LogLevel.DEBUG, `sync on mount`);
7883
sync(options, syncStatusCallback, downloadProgressCallback, handleBinaryVersionMismatchCallback);
7984

8085
if (options.checkFrequency === CheckFrequency.ON_APP_RESUME) {
8186
AppState.addEventListener('change', (newState: string) => {
8287
if (newState === 'active') {
88+
log(LogLevel.DEBUG, `sync on active appState`);
8389
sync(options, syncStatusCallback, downloadProgressCallback);
8490
}
8591
});

src/checkForUpdates.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { Platform } from 'react-native';
2+
import { LogLevel } from './enums/LogLevel.enum';
23
import { CodePushApiSdk } from './internals/CodePushApiSdk';
34
import type { ApiSdkQueryUpdatePackageInfo } from './internals/CodePushApiSdk.types';
45
import { NativeRNAppZungCodePushModule } from './internals/NativeRNAppZungCodePushModule';
@@ -84,7 +85,7 @@ export async function checkForUpdate(
8485
throw new Error('updateAppVersion should never be false');
8586
}
8687

87-
log('An update is available but it is not targeting the binary version of your app.');
88+
log(LogLevel.INFO, 'An update is available but it is not targeting the binary version of your app.');
8889
handleBinaryVersionMismatchCallback?.(update);
8990

9091
return null;

src/enums/LogLevel.enum.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
export enum LogLevel {
2+
DEBUG,
3+
INFO,
4+
WARN,
5+
ERROR,
6+
}

src/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ export * from './restartApp';
1010
export * from './sync';
1111
export * from './getClientUniqueId';
1212
export * from './resetClientUniqueId';
13+
export * from './logLevel';
1314

1415
export * from './types';
1516

@@ -18,3 +19,4 @@ export * from './enums/InstallMode.enum';
1819
export * from './enums/UpdateState.enum';
1920
export { DeploymentStatus } from './internals/CodePushApiSdk.types';
2021
export * from './enums/CheckFrequency.enum';
22+
export * from './enums/LogLevel.enum';

src/internals/RemotePackageImplementation.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { NativeEventEmitter } from 'react-native';
2+
import { LogLevel } from '../enums/LogLevel.enum';
23
import type { DownloadProgressCallback, LocalPackage, RemotePackage } from '../types';
34
import type { ApiSdkDownloadReportPackageInfo } from './CodePushApiSdk.types';
45
import { LocalPackageImplementation } from './LocalPackageImplementation';
@@ -42,7 +43,7 @@ export class RemotePackageImpl implements RemotePackage {
4243
const reportPromise = reportStatusDownload({
4344
label: this.label,
4445
}).catch((error) => {
45-
log(`Report download status failed: ${error}`);
46+
log(LogLevel.ERROR, `Report download status failed: ${error}`);
4647
});
4748
await Promise.race([timeoutPromise, reportPromise]);
4849
}

src/internals/shouldUpdateBeIgnored.ts

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { LogLevel } from '../enums/LogLevel.enum';
12
import type { RemotePackage, RollbackRetryOptions, SyncOptions } from '../types';
23
import { NativeRNAppZungCodePushModule } from './NativeRNAppZungCodePushModule';
34
import type { LatestRollbackInfo } from './types';
@@ -20,17 +21,17 @@ function validateLatestRollbackInfo(latestRollbackInfo: LatestRollbackInfo, pack
2021

2122
function validateRollbackRetryOptions(rollbackRetryOptions: RollbackRetryOptions) {
2223
if (typeof rollbackRetryOptions.delayInHours !== 'number') {
23-
log("The 'delayInHours' rollback retry parameter must be a number.");
24+
log(LogLevel.ERROR, "The 'delayInHours' rollback retry parameter must be a number.");
2425
return false;
2526
}
2627

2728
if (typeof rollbackRetryOptions.maxRetryAttempts !== 'number') {
28-
log("The 'maxRetryAttempts' rollback retry parameter must be a number.");
29+
log(LogLevel.ERROR, "The 'maxRetryAttempts' rollback retry parameter must be a number.");
2930
return false;
3031
}
3132

3233
if (rollbackRetryOptions.maxRetryAttempts < 1) {
33-
log("The 'maxRetryAttempts' rollback retry parameter cannot be less then 1.");
34+
log(LogLevel.ERROR, "The 'maxRetryAttempts' rollback retry parameter cannot be less then 1.");
3435
return false;
3536
}
3637

@@ -61,14 +62,14 @@ export async function shouldUpdateBeIgnored(remotePackage: RemotePackage | null
6162

6263
const latestRollbackInfo = await NativeRNAppZungCodePushModule.getLatestRollbackInfo();
6364
if (!validateLatestRollbackInfo(latestRollbackInfo, remotePackage.packageHash)) {
64-
log('The latest rollback info is not valid.');
65+
log(LogLevel.ERROR, 'The latest rollback info is not valid.');
6566
return true;
6667
}
6768

6869
const { delayInHours, maxRetryAttempts } = rollbackRetryOptions;
6970
const hoursSinceLatestRollback = (Date.now() - latestRollbackInfo.time) / (1000 * 60 * 60);
7071
if (hoursSinceLatestRollback >= delayInHours && maxRetryAttempts >= latestRollbackInfo.count) {
71-
log('Previous rollback should be ignored due to rollback retry options.');
72+
log(LogLevel.INFO, 'Previous rollback should be ignored due to rollback retry options.');
7273
return false;
7374
}
7475

src/internals/utils/log.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,12 @@
1+
import type { LogLevel } from '../../enums/LogLevel.enum';
2+
import { getLogLevel } from '../../logLevel';
3+
14
/* Logs messages to console with the [CodePush] prefix */
2-
export function log(message: string): void {
5+
export function log(level: LogLevel, message: string): void {
6+
const currentLogLevel = getLogLevel();
7+
if (level < currentLogLevel) {
8+
return;
9+
}
10+
311
console.log(`[CodePush] ${message}`);
412
}

src/internals/utils/requestFetchAdapter.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1+
import { LogLevel } from '../../enums/LogLevel.enum';
12
import type { Http } from '../CodePushApiSdk.types';
23
import { version } from '../version';
34
import { fetchRetry } from './fetchRetry';
5+
import { log } from './log';
46

57
export const requestFetchAdapter: Http.Requester = {
68
async request(method, url, requestBody) {
@@ -15,13 +17,19 @@ export const requestFetchAdapter: Http.Requester = {
1517
requestBody = JSON.stringify(requestBody);
1618
}
1719

20+
const requestId = Math.round(Math.random() * 10000);
21+
log(LogLevel.DEBUG, `[${requestId}] Will fetch ${method} ${url}`);
22+
1823
const response = await fetchRetry(url, {
1924
method,
2025
headers,
2126
body: requestBody,
2227
});
2328

2429
const statusCode = response.status;
30+
31+
log(LogLevel.DEBUG, `[${requestId}] Done fetching with status code ${statusCode}`);
32+
2533
const body = await response.text();
2634
return { statusCode, body };
2735
},

src/logLevel.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import { LogLevel } from './enums/LogLevel.enum';
2+
3+
let logLevel = LogLevel.INFO;
4+
5+
export const setLogLevel = (level: LogLevel) => {
6+
logLevel = level;
7+
};
8+
9+
export const getLogLevel = () => logLevel;

src/notifyAppReady.ts

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { AppState, type NativeEventSubscription } from 'react-native';
2+
import { LogLevel } from './enums/LogLevel.enum';
23
import { CodePushApiSdk } from './internals/CodePushApiSdk';
34
import { NativeRNAppZungCodePushModule } from './internals/NativeRNAppZungCodePushModule';
45
import { getConfiguration } from './internals/getConfiguration';
@@ -26,9 +27,17 @@ export const notifyAppReady = (() => {
2627
})();
2728

2829
async function notifyApplicationReadyInternal() {
30+
log(LogLevel.DEBUG, 'notifyApplicationReady');
31+
2932
await NativeRNAppZungCodePushModule.notifyApplicationReady();
3033
const statusReport = await NativeRNAppZungCodePushModule.getNewStatusReport();
31-
statusReport && tryReportStatus(statusReport); // Don't wait for this to complete.
34+
if (statusReport) {
35+
log(LogLevel.DEBUG, `tryReportStatus ${statusReport.status || '(no update)'}`);
36+
37+
tryReportStatus(statusReport); // Don't wait for this to complete.
38+
} else {
39+
log(LogLevel.DEBUG, `Nothing to report`);
40+
}
3241

3342
return statusReport;
3443
}
@@ -39,7 +48,7 @@ async function tryReportStatus(statusReport: StatusReport, retryOnAppResume?: Na
3948
const previousReleaseChannelPublicId = statusReport.previousReleaseChannelPublicId || config.releaseChannelPublicId;
4049
try {
4150
if (statusReport.appVersion) {
42-
log(`Reporting binary update (${statusReport.appVersion})`);
51+
log(LogLevel.INFO, `Reporting binary update (${statusReport.appVersion})`);
4352

4453
if (!config.releaseChannelPublicId) {
4554
throw new Error('Release channel is missing');
@@ -54,9 +63,9 @@ async function tryReportStatus(statusReport: StatusReport, retryOnAppResume?: Na
5463

5564
const label = statusReport.package.label;
5665
if (statusReport.status === 'DeploymentSucceeded') {
57-
log(`Reporting CodePush update success (${label})`);
66+
log(LogLevel.INFO, `Reporting CodePush update success (${label})`);
5867
} else {
59-
log(`Reporting CodePush update rollback (${label})`);
68+
log(LogLevel.INFO, `Reporting CodePush update rollback (${label})`);
6069
await NativeRNAppZungCodePushModule.setLatestRollbackInfo(statusReport.package.packageHash);
6170
}
6271

@@ -75,14 +84,15 @@ async function tryReportStatus(statusReport: StatusReport, retryOnAppResume?: Na
7584
NativeRNAppZungCodePushModule.recordStatusReported(statusReport);
7685
retryOnAppResume && retryOnAppResume.remove();
7786
} catch (e) {
78-
log(`Report status failed: ${JSON.stringify(statusReport)}`);
87+
log(LogLevel.WARN, `Report status failed: ${JSON.stringify(statusReport)}`);
7988
NativeRNAppZungCodePushModule.saveStatusReportForRetry(statusReport);
8089
// Try again when the app resumes
8190
if (!retryOnAppResume) {
8291
const resumeListener = AppState.addEventListener('change', async (newState) => {
8392
if (newState !== 'active') return;
8493
const refreshedStatusReport = await NativeRNAppZungCodePushModule.getNewStatusReport();
8594
if (refreshedStatusReport) {
95+
log(LogLevel.DEBUG, `tryReportStatus on active appState ${statusReport.status || '(no update)'}`);
8696
tryReportStatus(refreshedStatusReport, resumeListener);
8797
} else {
8898
resumeListener && resumeListener.remove();

0 commit comments

Comments
 (0)