Skip to content

Commit

Permalink
cleanup all console/log statements
Browse files Browse the repository at this point in the history
-- Replace all uses of console.log or console.debug with the functions from logger.ts (logDebug, logWarn, displayError). This ensures that all log statements are recorded by both the Javascript console AND the Cordova Logger plugin
-- Format all these log statements concisely and in a unified way (longer statements make use of `template strings` with interpolation, and the statements are put on as few lines as possible to mimimize clutter)
-- Remove log statements that are deemed redundant or excessive (we want to be thorough but not spammy - avoid log statements that run on every single re-render)
  • Loading branch information
JGreenlee committed Jan 26, 2024
1 parent adc6620 commit 0a8ed76
Show file tree
Hide file tree
Showing 34 changed files with 177 additions and 267 deletions.
2 changes: 0 additions & 2 deletions www/js/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,6 @@ const App = () => {
setPermissionsPopupVis,
};

console.debug('onboardingState in App', onboardingState);

let appContent;
if (onboardingState == null) {
// if onboarding state is not yet determined, show a loading spinner
Expand Down
10 changes: 6 additions & 4 deletions www/js/components/QrCode.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ we can remove this wrapper and just use the QRCode component directly */

import React from 'react';
import QRCode from 'react-qr-code';
import { logWarn } from '../plugin/logger';
import { logDebug, logWarn } from '../plugin/logger';

export function shareQR(message) {
/*code adapted from demo of react-qr-code*/
Expand All @@ -29,11 +29,13 @@ export function shareQR(message) {
window['plugins'].socialsharing.shareWithOptions(
prepopulateQRMessage,
(result) => {
console.log('Share completed? ' + result.completed); // On Android apps mostly return false even while it's true
console.log('Shared to app: ' + result.app); // On Android result.app is currently empty. On iOS it's empty when sharing is cancelled (result.completed=false)
// On Android apps mostly return completed=false even while it's true
// On Android result.app is currently empty. On iOS it's empty when sharing is cancelled (result.completed=false)
logDebug(`socialsharing: share completed? ' + ${result.completed};
shared to app: ${result.app}`);
},
(msg) => {
console.log('Sharing failed with message: ' + msg);
logWarn('socialsharing: failed with message: ' + msg);
},
);
};
Expand Down
12 changes: 2 additions & 10 deletions www/js/components/charting.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import color from 'color';
import { getBaseModeByKey } from '../diary/diaryHelper';
import { readableLabelToKey } from '../survey/multilabel/confirmHelper';
import { logDebug } from '../plugin/logger';

export const defaultPalette = [
'#c95465', // red oklch(60% 0.15 14)
Expand Down Expand Up @@ -49,11 +50,9 @@ export function getChartHeight(

function getBarHeight(stacks) {
let totalHeight = 0;
console.log('ctx stacks', stacks.x);
for (let val in stacks.x) {
if (!val.startsWith('_')) {
totalHeight += stacks.x[val];
console.log('ctx added ', val);
}
}
return totalHeight;
Expand Down Expand Up @@ -82,14 +81,7 @@ function createDiagonalPattern(color = 'black') {
export function getMeteredBackgroundColor(meter, currDataset, barCtx, colors, darken = 0) {
if (!barCtx || !currDataset) return;
let bar_height = getBarHeight(barCtx.parsed._stacks);
console.debug(
'bar height for',
barCtx.raw.y,
' is ',
bar_height,
'which in chart is',
currDataset,
);
logDebug(`bar height for ${barCtx.raw.y} is ${bar_height} which in chart is ${currDataset}`);
let meteredColor;
if (bar_height > meter.high) meteredColor = colors.danger;
else if (bar_height > meter.middle) meteredColor = colors.warn;
Expand Down
12 changes: 5 additions & 7 deletions www/js/config/dynamicConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,15 +197,15 @@ function extractSubgroup(token: string, config: AppConfig): string | undefined {
}),
);
} else {
console.log('subgroup ' + tokenParts[2] + ' found in list ' + config.opcode.subgroups);
logDebug('subgroup ' + tokenParts[2] + ' found in list ' + config.opcode.subgroups);
return tokenParts[2];
}
} else {
if (tokenParts[2] != 'default') {
// subpart not in config list
throw new Error(i18next.t('config.invalid-subgroup-no-default', { token: token }));
} else {
console.log("no subgroups in config, 'default' subgroup found in token ");
logDebug("no subgroups in config, 'default' subgroup found in token ");
return tokenParts[2];
}
}
Expand All @@ -216,7 +216,7 @@ function extractSubgroup(token: string, config: AppConfig): string | undefined {
* first is already handled in extractStudyName, second is handled
* by default since download will fail if it is invalid
*/
console.log('Old-style study, expecting token without a subgroup...');
logDebug('Old-style study, expecting token without a subgroup...');
return undefined;
}
}
Expand Down Expand Up @@ -251,10 +251,8 @@ function loadNewConfig(newToken: string, existingVersion?: number): Promise<bool
// loaded new config, so it is both ready and changed
return Promise.all([storeConfigPromise, storeInKVStorePromise])
.then(([result, kvStoreResult]) => {
logDebug(
'UI_CONFIG: Stored dynamic config in KVStore successfully, result = ' +
JSON.stringify(kvStoreResult),
);
logDebug(`UI_CONFIG: Stored dynamic config in KVStore successfully,
result = ${JSON.stringify(kvStoreResult)}`);
storedConfig = toSaveConfig;
configChanged = true;
return true;
Expand Down
11 changes: 5 additions & 6 deletions www/js/control/ControlCollectionHelper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Dialog, Button, Switch, Text, useTheme, TextInput } from 'react-native-
import { useTranslation } from 'react-i18next';
import ActionMenu from '../components/ActionMenu';
import { settingStyles } from './ProfileSettings';
import { displayError } from '../plugin/logger';
import { displayError, displayErrorMsg, logDebug } from '../plugin/logger';

type collectionConfig = {
is_duty_cycling: boolean;
Expand All @@ -27,7 +27,7 @@ export async function forceTransition(transition) {
window.alert('success -> ' + result);
} catch (err) {
window.alert('error -> ' + err);
console.log('error forcing state', err);
displayError(err, 'error forcing state');
}
}

Expand All @@ -48,7 +48,6 @@ export async function isMediumAccuracy() {
return undefined; // config not loaded when loading ui, set default as false
} else {
const v = await accuracy2String(config);
console.log('window platform is', window['cordova'].platformId);
if (window['cordova'].platformId == 'ios') {
return (
v != 'kCLLocationAccuracyBestForNavigation' &&
Expand All @@ -58,7 +57,7 @@ export async function isMediumAccuracy() {
} else if (window['cordova'].platformId == 'android') {
return v != 'PRIORITY_HIGH_ACCURACY';
} else {
window.alert('Emission does not support this platform');
displayErrorMsg('Emission does not support this platform: ' + window['cordova'].platformId);
}
}
}
Expand All @@ -82,7 +81,7 @@ export async function helperToggleLowAccuracy() {
}
try {
let set = await setConfig(tempConfig);
console.log('setConfig Sucess');
logDebug('setConfig Sucess');
} catch (err) {
displayError(err, 'Error while setting collection config');
}
Expand Down Expand Up @@ -159,7 +158,7 @@ const ControlCollectionHelper = ({ editVis, setEditVis }) => {
*/

async function saveAndReload() {
console.log('new config = ', localConfig);
logDebug('new config = ' + JSON.stringify(localConfig));
try {
let set = await setConfig(localConfig);
setEditVis(false);
Expand Down
1 change: 0 additions & 1 deletion www/js/control/ControlDataTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { DataTable } from 'react-native-paper';

// val with explicit call toString() to resolve bool values not showing
const ControlDataTable = ({ controlData }) => {
console.log('Printing data trying to tabulate', controlData);
return (
//rows require unique keys!
<DataTable style={styles.table}>
Expand Down
5 changes: 1 addition & 4 deletions www/js/control/ControlSyncHelper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,6 @@ export const ForceSyncRow = ({ getState }) => {
async function forceSync() {
try {
let addedEvent = await addStatEvent(statKeys.BUTTON_FORCE_SYNC);
console.log('Added ' + statKeys.BUTTON_FORCE_SYNC + ' event');

let sync = await forcePluginSync();
/*
* Change to sensorKey to "background/location" after fixing issues
Expand Down Expand Up @@ -198,7 +196,7 @@ const ControlSyncHelper = ({ editVis, setEditVis }) => {
* Functions to edit and save values
*/
async function saveAndReload() {
console.log('new config = ' + localConfig);
logDebug('saveAndReload: new config = ' + JSON.stringify(localConfig));
try {
let set = setConfig(localConfig);
//NOTE -- we need to make sure we update these settings in ProfileSettings :) -- getting rid of broadcast handling for migration!!
Expand All @@ -212,7 +210,6 @@ const ControlSyncHelper = ({ editVis, setEditVis }) => {
curr_sync_interval: (localConfig as syncConfig).sync_interval,
});
} catch (err) {
console.log('error with setting sync config', err);
displayError(err, 'Error while setting sync config');
}
}
Expand Down
14 changes: 7 additions & 7 deletions www/js/control/LogPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { FlashList } from '@shopify/flash-list';
import { DateTime } from 'luxon';
import AlertBar from './AlertBar';
import { sendEmail } from './emailService';
import { displayError, logDebug } from '../plugin/logger';

type loadStats = { currentStart: number; gotMaxIndex: boolean; reachedEnd: boolean };

Expand All @@ -31,7 +32,7 @@ const LogPage = ({ pageVis, setPageVis }) => {
async function refreshEntries() {
try {
let maxIndex = await window['Logger'].getMaxIndex();
console.log('maxIndex = ' + maxIndex);
logDebug('Logger maxIndex = ' + maxIndex);
let tempStats = {} as loadStats;
tempStats.currentStart = maxIndex;
tempStats.gotMaxIndex = true;
Expand All @@ -40,7 +41,7 @@ const LogPage = ({ pageVis, setPageVis }) => {
setEntries([]);
} catch (error) {
let errorString = t('errors.while-max-index') + JSON.stringify(error, null, 2);
console.log(errorString);
displayError(error, errorString);
setMaxMessage(errorString);
setMaxErrorVis(true);
} finally {
Expand All @@ -62,17 +63,16 @@ const LogPage = ({ pageVis, setPageVis }) => {
}

async function addEntries() {
console.log('calling addEntries');
setIsFetching(true);
let start = loadStats?.currentStart ? loadStats.currentStart : 0; //set a default start to prevent initial fetch error
try {
let entryList = await window['Logger'].getMessagesFromIndex(start, RETRIEVE_COUNT);
processEntries(entryList);
console.log('entry list size = ' + entries.length);
logDebug('addEntries: entry list size = ' + entries.length);
setIsFetching(false);
} catch (error) {
let errStr = t('errors.while-log-messages') + JSON.stringify(error, null, 2);
console.log(errStr);
displayError(error, errStr);
setLogMessage(errStr);
setLogErrorVis(true);
setIsFetching(false);
Expand All @@ -87,11 +87,11 @@ const LogPage = ({ pageVis, setPageVis }) => {
tempEntries.push(e);
});
if (entryList.length == 0) {
console.log('Reached the end of the scrolling');
logDebug('LogPage reached the end of the scrolling');
tempLoadStats.reachedEnd = true;
} else {
tempLoadStats.currentStart = entryList[entryList.length - 1].ID;
console.log('new start index = ' + loadStats?.currentStart);
logDebug('LogPage new start index = ' + loadStats?.currentStart);
}
setEntries([...entries].concat(tempEntries)); //push the new entries onto the list
setLoadStats(tempLoadStats);
Expand Down
48 changes: 17 additions & 31 deletions www/js/control/ProfileSettings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -158,14 +158,12 @@ const ProfileSettings = () => {
});
}

// setTemplateText(tempUiConfig.intro.translated_text);
// console.log("translated text is??", templateText);
setUiConfig(tempUiConfig);
refreshScreen();
}

async function refreshCollectSettings() {
console.debug('about to refreshCollectSettings, collectSettings = ', collectSettings);
logDebug('refreshCollectSettings: collectSettings = ' + JSON.stringify(collectSettings));
const newCollectSettings: any = {};

// // refresh collect plugin configuration
Expand All @@ -190,17 +188,15 @@ const ProfileSettings = () => {
useEffect(() => {
if (editCollectionVis == false) {
setTimeout(() => {
console.log('closed editor, time to refresh collect');
logDebug('closed editor, time to refreshCollectSettings');
refreshCollectSettings();
}, 1000);
}
}, [editCollectionVis]);

async function refreshNotificationSettings() {
logDebug(
'about to refreshNotificationSettings, notificationSettings = ' +
JSON.stringify(notificationSettings),
);
logDebug(`about to refreshNotificationSettings,
notificationSettings = ${JSON.stringify(notificationSettings)}`);
const newNotificationSettings: any = {};

if (uiConfig?.reminderSchemes) {
Expand All @@ -212,12 +208,8 @@ const ProfileSettings = () => {
let resultList = await Promise.all(promiseList);
const prefs = resultList[0];
const scheduledNotifs = resultList[1];
logDebug(
'prefs and scheduled notifs\n' +
JSON.stringify(prefs) +
'\n-\n' +
JSON.stringify(scheduledNotifs),
);
logDebug(`prefs - scheduled notifs:
${JSON.stringify(prefs)}\n - \n${JSON.stringify(scheduledNotifs)}`);

const m = DateTime.fromFormat(prefs.reminder_time_of_day, 'HH:mm');
newNotificationSettings.prefReminderTimeVal = m.toJSDate();
Expand All @@ -226,22 +218,17 @@ const ProfileSettings = () => {
newNotificationSettings.scheduledNotifs = scheduledNotifs;
}

logDebug(
'notification settings before and after\n' +
JSON.stringify(notificationSettings) +
'\n-\n' +
JSON.stringify(newNotificationSettings),
);
logDebug(`notification settings before - after:
${JSON.stringify(notificationSettings)} - ${JSON.stringify(newNotificationSettings)}`);
setNotificationSettings(newNotificationSettings);
}

async function getSyncSettings() {
console.log('getting sync settings');
const newSyncSettings: any = {};
getHelperSyncSettings().then((showConfig) => {
newSyncSettings.show_config = showConfig;
setSyncSettings(newSyncSettings);
console.log('sync settings are ', syncSettings);
logDebug('sync settings are: ' + JSON.stringify(syncSettings));
});
}

Expand All @@ -254,8 +241,8 @@ const ProfileSettings = () => {
getSettings().then(
(response) => {
const newConnectSettings: any = {};
logDebug('getConnectURL: got response.connectUrl = ' + response.connectUrl);
newConnectSettings.url = response.connectUrl;
console.log(response);
setConnectSettings(newConnectSettings);
},
(error) => {
Expand Down Expand Up @@ -333,14 +320,14 @@ const ProfileSettings = () => {
//for now, use window.cordova.platformId

function parseState(state) {
console.log('state in parse state is', state);
logDebug(`parseState: state = ${state};
platformId = ${window['cordova'].platformId}`);
if (state) {
console.log('state in parse state exists', window['cordova'].platformId);
if (window['cordova'].platformId == 'android') {
console.log('ANDROID state in parse state is', state.substring(12));
logDebug('platform ANDROID; parsed state will be ' + state.substring(12));
return state.substring(12);
} else if (window['cordova'].platformId == 'ios') {
console.log('IOS state in parse state is', state.substring(6));
logDebug('platform IOS; parsed state will be ' + state.substring(6));
return state.substring(6);
}
}
Expand All @@ -349,7 +336,7 @@ const ProfileSettings = () => {
async function invalidateCache() {
window['cordova'].plugins.BEMUserCache.invalidateAllCache().then(
(result) => {
console.log('invalidate result', result);
logDebug('invalidateCache: result = ' + JSON.stringify(result));
setCacheResult(result);
setInvalidateSuccessVis(true);
},
Expand Down Expand Up @@ -384,7 +371,6 @@ const ProfileSettings = () => {
//conditional creation of setting sections

let logUploadSection;
console.debug('appConfg: support_upload:', appConfig?.profile_controls?.support_upload);
if (appConfig?.profile_controls?.support_upload) {
logUploadSection = (
<SettingRow
Expand All @@ -409,7 +395,7 @@ const ProfileSettings = () => {
<SettingRow
textKey="control.upcoming-notifications"
iconName="bell-check"
action={() => console.log('')}></SettingRow>
action={() => {}}></SettingRow>
<ControlDataTable controlData={notificationSettings.scheduledNotifs}></ControlDataTable>
</>
);
Expand Down Expand Up @@ -507,7 +493,7 @@ const ProfileSettings = () => {
<SettingRow
textKey="control.app-version"
iconName="application"
action={() => console.log('')}
action={() => {}}
desc={appVersion.current}></SettingRow>
</ScrollView>

Expand Down
Loading

0 comments on commit 0a8ed76

Please sign in to comment.