From 0a8ed767b63d83c666bc64a3c76dd66bf85b0cd7 Mon Sep 17 00:00:00 2001 From: Jack Greenlee Date: Fri, 26 Jan 2024 15:21:45 -0500 Subject: [PATCH] cleanup all console/log statements -- 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) --- www/js/App.tsx | 2 - www/js/components/QrCode.tsx | 10 ++-- www/js/components/charting.ts | 12 +---- www/js/config/dynamicConfig.ts | 12 ++--- www/js/control/ControlCollectionHelper.tsx | 11 ++-- www/js/control/ControlDataTable.tsx | 1 - www/js/control/ControlSyncHelper.tsx | 5 +- www/js/control/LogPage.tsx | 14 ++--- www/js/control/ProfileSettings.tsx | 48 ++++++----------- www/js/control/uploadService.ts | 17 +++--- www/js/diary/addressNamesHelper.ts | 12 ++--- www/js/diary/timelineHelper.ts | 53 ++++++------------ www/js/i18nextInit.ts | 3 +- www/js/metrics/CarbonFootprintCard.tsx | 9 ++-- www/js/metrics/CarbonTextCard.tsx | 4 +- www/js/metrics/customMetricsHelper.ts | 1 - www/js/metrics/metricsHelper.ts | 21 +++----- www/js/onboarding/OnboardingStack.tsx | 2 - www/js/onboarding/WelcomePage.tsx | 6 +-- www/js/plugin/clientStats.ts | 5 +- www/js/plugin/logger.ts | 6 +-- www/js/plugin/storage.ts | 22 +++----- www/js/splash/customURL.ts | 6 ++- www/js/splash/notifScheduler.ts | 11 +--- www/js/splash/remoteNotifyHandler.ts | 4 +- www/js/splash/startprefs.ts | 1 - www/js/splash/storeDeviceSettings.ts | 15 ++---- www/js/survey/enketo/AddNoteButton.tsx | 2 +- www/js/survey/enketo/AddedNotesList.tsx | 2 +- www/js/survey/enketo/EnketoModal.tsx | 8 +-- www/js/survey/inputMatcher.ts | 39 ++++++-------- www/js/survey/multilabel/confirmHelper.ts | 14 ++--- www/js/useAppStateChange.ts | 3 +- www/js/usePermissionStatus.ts | 63 +++++++++++----------- 34 files changed, 177 insertions(+), 267 deletions(-) diff --git a/www/js/App.tsx b/www/js/App.tsx index f43f006d9..ca0cdd406 100644 --- a/www/js/App.tsx +++ b/www/js/App.tsx @@ -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 diff --git a/www/js/components/QrCode.tsx b/www/js/components/QrCode.tsx index 195e124a9..c8547eaf8 100644 --- a/www/js/components/QrCode.tsx +++ b/www/js/components/QrCode.tsx @@ -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*/ @@ -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); }, ); }; diff --git a/www/js/components/charting.ts b/www/js/components/charting.ts index 85b98bbbe..f536fc04f 100644 --- a/www/js/components/charting.ts +++ b/www/js/components/charting.ts @@ -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) @@ -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; @@ -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; diff --git a/www/js/config/dynamicConfig.ts b/www/js/config/dynamicConfig.ts index 1b7176674..9773a1ead 100644 --- a/www/js/config/dynamicConfig.ts +++ b/www/js/config/dynamicConfig.ts @@ -197,7 +197,7 @@ 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 { @@ -205,7 +205,7 @@ function extractSubgroup(token: string, config: AppConfig): string | undefined { // 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]; } } @@ -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; } } @@ -251,10 +251,8 @@ function loadNewConfig(newToken: string, existingVersion?: number): Promise { - 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; diff --git a/www/js/control/ControlCollectionHelper.tsx b/www/js/control/ControlCollectionHelper.tsx index b8fb160bc..993f3724f 100644 --- a/www/js/control/ControlCollectionHelper.tsx +++ b/www/js/control/ControlCollectionHelper.tsx @@ -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; @@ -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'); } } @@ -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' && @@ -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); } } } @@ -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'); } @@ -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); diff --git a/www/js/control/ControlDataTable.tsx b/www/js/control/ControlDataTable.tsx index 932762400..ea53bbd52 100644 --- a/www/js/control/ControlDataTable.tsx +++ b/www/js/control/ControlDataTable.tsx @@ -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! diff --git a/www/js/control/ControlSyncHelper.tsx b/www/js/control/ControlSyncHelper.tsx index 576f71909..cdc1a8e2a 100644 --- a/www/js/control/ControlSyncHelper.tsx +++ b/www/js/control/ControlSyncHelper.tsx @@ -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 @@ -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!! @@ -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'); } } diff --git a/www/js/control/LogPage.tsx b/www/js/control/LogPage.tsx index 1ac0b3557..098592dee 100644 --- a/www/js/control/LogPage.tsx +++ b/www/js/control/LogPage.tsx @@ -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 }; @@ -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; @@ -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 { @@ -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); @@ -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); diff --git a/www/js/control/ProfileSettings.tsx b/www/js/control/ProfileSettings.tsx index 6951e889b..3af63b2c4 100644 --- a/www/js/control/ProfileSettings.tsx +++ b/www/js/control/ProfileSettings.tsx @@ -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 @@ -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) { @@ -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(); @@ -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)); }); } @@ -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) => { @@ -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); } } @@ -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); }, @@ -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 = ( { console.log('')}> + action={() => {}}> ); @@ -507,7 +493,7 @@ const ProfileSettings = () => { console.log('')} + action={() => {}} desc={appVersion.current}> diff --git a/www/js/control/uploadService.ts b/www/js/control/uploadService.ts index 163b65b2f..c0b0213ea 100644 --- a/www/js/control/uploadService.ts +++ b/www/js/control/uploadService.ts @@ -19,7 +19,6 @@ async function getUploadConfig() { let response = await fetch('json/uploadConfig.json.sample'); let uploadConfig = await response.json(); logDebug('default uploadConfigString = ' + JSON.stringify(uploadConfig['url'])); - console.log('default uploadConfigString = ' + JSON.stringify(uploadConfig['url'])); url.push(uploadConfig['url']); resolve(url); } catch (err) { @@ -41,32 +40,30 @@ function onUploadError(err) { function readDBFile(parentDir, database, callbackFn) { return new Promise((resolve, reject) => { window['resolveLocalFileSystemURL'](parentDir, (fs) => { - console.log('resolving file system as ', fs); + logDebug('resolving file system as ' + JSON.stringify(fs)); fs.filesystem.root.getFile( fs.fullPath + database, null, (fileEntry) => { - console.log(fileEntry); + logDebug('fileEntry = ' + JSON.stringify(fileEntry)); fileEntry.file((file) => { - console.log(file); + logDebug('file = ' + JSON.stringify(file)); const reader = new FileReader(); reader.onprogress = (report) => { - console.log('Current progress is ' + JSON.stringify(report)); + logDebug('Current progress is ' + JSON.stringify(report)); if (callbackFn != undefined) { callbackFn((report.loaded * 100) / report.total); } }; reader.onerror = (error) => { - console.log(this.error); + logDebug('Error while reading file ' + JSON.stringify(this.error)); reject({ error: { message: this.error } }); }; reader.onload = () => { - console.log( - 'Successful file read with ' + this.result?.['byteLength'] + ' characters', - ); + logDebug('Successful file read with ' + this.result?.['byteLength'] + ' characters'); resolve(new DataView(this.result as ArrayBuffer)); }; @@ -106,7 +103,7 @@ export async function uploadFile(database, reason) { logInfo('Going to upload ' + database); try { let binString: any = await readDBFile(parentDir, database, undefined); - console.log('Uploading file of size ' + binString['byteLength']); + logDebug('Uploading file of size ' + binString['byteLength']); const params = { reason: reason, tz: Intl.DateTimeFormat().resolvedOptions().timeZone, diff --git a/www/js/diary/addressNamesHelper.ts b/www/js/diary/addressNamesHelper.ts index b66eee8e8..30740ad19 100644 --- a/www/js/diary/addressNamesHelper.ts +++ b/www/js/diary/addressNamesHelper.ts @@ -67,7 +67,7 @@ export function useLocalStorage(key: string, initialValue: T) { window.localStorage.setItem(key, JSON.stringify(valueToStore)); } } catch (error) { - console.error(error); + displayError(error); } } return [storedValue, setValue]; @@ -110,15 +110,11 @@ async function fetchNominatimLocName(loc_geojson) { const coordsStr = loc_geojson.coordinates.toString(); const cachedResponse = localStorage.getItem(coordsStr); if (cachedResponse) { - console.log( - 'fetchNominatimLocName: found cached response for ', - coordsStr, - cachedResponse, - 'skipping fetch', - ); + logDebug(`fetchNominatimLocName: found cached response for ${coordsStr} = + ${cachedResponse}, skipping fetch`); return; } - console.log('Getting location name for ', coordsStr); + logDebug('Getting location name for ' + JSON.stringify(coordsStr)); const url = 'https://nominatim.openstreetmap.org/reverse?format=json&lat=' + loc_geojson.coordinates[1] + diff --git a/www/js/diary/timelineHelper.ts b/www/js/diary/timelineHelper.ts index d22c4f956..f140f1750 100644 --- a/www/js/diary/timelineHelper.ts +++ b/www/js/diary/timelineHelper.ts @@ -351,12 +351,10 @@ function transitionTrip2TripObj(trip: Array): Promise>) => { @@ -375,12 +373,8 @@ function transitionTrip2TripObj(trip: Array): Promise): Promise>) { .slice(processedUntil) .findIndex(isEndingTransition); if (foundEndTransitionIndex == -1) { - logDebug( - "Can't find end for trip starting at " + - JSON.stringify(transitionList[currStartTransitionIndex]) + - ' dropping it', - ); + logDebug(`Can't find end for trip starting at: + ${JSON.stringify(transitionList[currStartTransitionIndex])} - dropping it`); processedUntil = transitionList.length; } else { currEndTransitionIndex = processedUntil + foundEndTransitionIndex; processedUntil = currEndTransitionIndex; logDebug(`currEndTransitionIndex ${currEndTransitionIndex}`); - logDebug( - 'Unprocessed trip starting at ' + - JSON.stringify(transitionList[currStartTransitionIndex]) + - ' ends at ' + - JSON.stringify(transitionList[currEndTransitionIndex]), - ); + logDebug(`Unprocessed trip, + starting at: ${JSON.stringify(transitionList[currStartTransitionIndex])}; + ends at: ${JSON.stringify(transitionList[currEndTransitionIndex])}`); tripList.push([ transitionList[currStartTransitionIndex], transitionList[currEndTransitionIndex], @@ -528,11 +511,7 @@ export function readUnprocessedTrips( lastProcessedTrip?: CompositeTrip, ) { const tq = { key: 'write_ts', startTs, endTs }; - logDebug( - 'about to query for unprocessed trips from ' + - DateTime.fromSeconds(tq.startTs).toLocaleString(DateTime.DATETIME_MED) + - DateTime.fromSeconds(tq.endTs).toLocaleString(DateTime.DATETIME_MED), - ); + logDebug(`about to query for unprocessed trips from ${tq.startTs} to ${tq.endTs}`); const getMessageMethod = window['cordova'].plugins.BEMUserCache.getMessagesForInterval; return getUnifiedDataForInterval('statemachine/transition', tq, getMessageMethod).then( (transitionList: Array>) => { diff --git a/www/js/i18nextInit.ts b/www/js/i18nextInit.ts index 3137d78e6..e42a130ac 100644 --- a/www/js/i18nextInit.ts +++ b/www/js/i18nextInit.ts @@ -18,7 +18,7 @@ On dev builds, the fallback translation is prefixed with a globe emoji so it's e function mergeInTranslations(lang, fallbackLang) { Object.entries(fallbackLang).forEach(([key, value]) => { if (lang[key] === undefined) { - console.warn(`Missing translation for key '${key}'`); + logWarn(`Missing translation for key '${key}'`); if (__DEV__) { if (typeof value === 'string') { lang[key] = `🌐${value}`; @@ -66,6 +66,7 @@ export default i18next; // Next, register the translations for react-native-paper-dates import { en, es, fr, it, registerTranslation } from 'react-native-paper-dates'; +import { logWarn } from './plugin/logger'; const rnpDatesLangs = { en, es, diff --git a/www/js/metrics/CarbonFootprintCard.tsx b/www/js/metrics/CarbonFootprintCard.tsx index ff06e8632..56e955f60 100644 --- a/www/js/metrics/CarbonFootprintCard.tsx +++ b/www/js/metrics/CarbonFootprintCard.tsx @@ -22,6 +22,7 @@ import BarChart from '../components/BarChart'; import ChangeIndicator, { CarbonChange } from './ChangeIndicator'; import color from 'color'; import { useAppTheme } from '../appTheme'; +import { logDebug, logWarn } from '../plugin/logger'; type Props = { userMetrics?: MetricsData; aggMetrics?: MetricsData }; const CarbonFootprintCard = ({ userMetrics, aggMetrics }: Props) => { @@ -109,7 +110,8 @@ const CarbonFootprintCard = ({ userMetrics, aggMetrics }: Props) => { if (aggMetrics?.distance?.length) { //separate data into weeks const thisWeekDistance = segmentDaysByWeeks(aggMetrics?.distance, 1)[0]; - console.log('testing agg metrics', aggMetrics, thisWeekDistance); + logDebug(`groupCarbonRecords: aggMetrics = ${JSON.stringify(aggMetrics)}; + thisWeekDistance = ${JSON.stringify(thisWeekDistance)}`); let aggThisWeekModeMap = parseDataFromMetrics(thisWeekDistance, 'aggregate'); let aggThisWeekSummary = generateSummaryFromData(aggThisWeekModeMap, 'distance'); @@ -120,7 +122,7 @@ const CarbonFootprintCard = ({ userMetrics, aggMetrics }: Props) => { for (let i in aggThisWeekSummary) { aggCarbonData.push(aggThisWeekSummary[i]); if (isNaN(aggCarbonData[i].values)) { - console.warn(`WARNING in calculating groupCarbonRecords: value is NaN for mode + logWarn(`WARNING in calculating groupCarbonRecords: value is NaN for mode ${aggCarbonData[i].key}, changing to 0`); aggCarbonData[i].values = 0; } @@ -132,7 +134,7 @@ const CarbonFootprintCard = ({ userMetrics, aggMetrics }: Props) => { low: getFootprintForMetrics(aggCarbonData, 0), high: getFootprintForMetrics(aggCarbonData, getHighestFootprint()), }; - console.log('testing group past week', aggCarbon); + logDebug(`groupCarbonRecords: aggCarbon = ${JSON.stringify(aggCarbon)}`); groupRecords.push({ label: t('main-metrics.unlabeled'), x: aggCarbon.high - aggCarbon.low, @@ -157,7 +159,6 @@ const CarbonFootprintCard = ({ userMetrics, aggMetrics }: Props) => { tempChartData = tempChartData.concat(groupCarbonRecords); } tempChartData = tempChartData.reverse(); - console.log('testing chart data', tempChartData); return tempChartData; }, [userCarbonRecords, groupCarbonRecords]); diff --git a/www/js/metrics/CarbonTextCard.tsx b/www/js/metrics/CarbonTextCard.tsx index fe26e7a22..bf89bdb49 100644 --- a/www/js/metrics/CarbonTextCard.tsx +++ b/www/js/metrics/CarbonTextCard.tsx @@ -17,7 +17,7 @@ import { segmentDaysByWeeks, MetricsSummary, } from './metricsHelper'; -import { logWarn } from '../plugin/logger'; +import { logDebug, logWarn } from '../plugin/logger'; type Props = { userMetrics?: MetricsData; aggMetrics?: MetricsData }; const CarbonTextCard = ({ userMetrics, aggMetrics }: Props) => { @@ -112,7 +112,7 @@ const CarbonTextCard = ({ userMetrics, aggMetrics }: Props) => { low: getFootprintForMetrics(aggCarbonData, 0), high: getFootprintForMetrics(aggCarbonData, getHighestFootprint()), }; - console.log('testing group past week', aggCarbon); + logDebug(`groupText: aggCarbon = ${JSON.stringify(aggCarbon)}`); const label = t('main-metrics.average'); if (aggCarbon.low == aggCarbon.high) groupText.push({ label: label, value: `${Math.round(aggCarbon.low)}` }); diff --git a/www/js/metrics/customMetricsHelper.ts b/www/js/metrics/customMetricsHelper.ts index 1831f51c6..c354d1f58 100644 --- a/www/js/metrics/customMetricsHelper.ts +++ b/www/js/metrics/customMetricsHelper.ts @@ -45,7 +45,6 @@ function populateCustomMETs() { // we assume that they specify -1 instead, and we will // map -1 to Number.MAX_VALUE here by iterating over all the ranges for (const rangeName in currMET) { - // console.log("Handling range ", rangeName); currMET[rangeName].range = currMET[rangeName].range.map((i) => i == -1 ? Number.MAX_VALUE : i, ); diff --git a/www/js/metrics/metricsHelper.ts b/www/js/metrics/metricsHelper.ts index 7ed348b75..9dbc23c82 100644 --- a/www/js/metrics/metricsHelper.ts +++ b/www/js/metrics/metricsHelper.ts @@ -1,6 +1,7 @@ import { DateTime } from 'luxon'; import { formatForDisplay } from '../config/useImperialConfig'; import { DayOfMetricData } from './metricsTypes'; +import { logDebug } from '../plugin/logger'; export function getUniqueLabelsForDays(metricDataDays: DayOfMetricData[]) { const uniqueLabels: string[] = []; @@ -86,7 +87,8 @@ export function calculatePercentChange(pastWeekRange, previousWeekRange) { } export function parseDataFromMetrics(metrics, population) { - console.log('Called parseDataFromMetrics on ', metrics); + logDebug(`parseDataFromMetrics: metrics = ${JSON.stringify(metrics)}; + population = ${population}`); let mode_bins: { [k: string]: [number, number, string][] } = {}; metrics?.forEach((metric) => { let onFootVal = 0; @@ -115,7 +117,7 @@ export function parseDataFromMetrics(metrics, population) { //this section handles user lables, assuming 'label_' prefix if (field.startsWith('label_')) { let actualMode = field.slice(6, field.length); //remove prefix - console.log('Mapped field ' + field + ' to mode ' + actualMode); + logDebug('Mapped field ' + field + ' to mode ' + actualMode); if (!(actualMode in mode_bins)) { mode_bins[actualMode] = []; } @@ -137,7 +139,7 @@ export function parseDataFromMetrics(metrics, population) { export type MetricsSummary = { key: string; values: number }; export function generateSummaryFromData(modeMap, metric) { - console.log('Invoked getSummaryDataRaw on ', modeMap, 'with', metric); + logDebug(`Invoked getSummaryDataRaw on ${JSON.stringify(modeMap)} with ${metric}`); let summaryMap: MetricsSummary[] = []; @@ -175,19 +177,12 @@ export function isCustomLabels(modeMap) { const distanceKeys = modeMap.map((e) => e.key); const isSensedKeys = distanceKeys.map(isSensed); const isCustomKeys = distanceKeys.map(isCustom); - console.log( - 'Checking metric keys', - distanceKeys, - ' sensed ', - isSensedKeys, - ' custom ', - isCustomKeys, - ); + logDebug(`Checking metric keys ${distanceKeys}; sensed ${isSensedKeys}; custom ${isCustomKeys}`); const isAllCustomForMetric = isAllCustom(isSensedKeys, isCustomKeys); metricSummaryChecksSensed.push(!isAllCustomForMetric); metricSummaryChecksCustom.push(!!isAllCustomForMetric); - - console.log('overall custom/not results for each metric = ', metricSummaryChecksCustom); + logDebug(`overall custom/not results for each metric + is ${JSON.stringify(metricSummaryChecksCustom)}`); return isAllCustom(metricSummaryChecksSensed, metricSummaryChecksCustom); } diff --git a/www/js/onboarding/OnboardingStack.tsx b/www/js/onboarding/OnboardingStack.tsx index 30b725ea9..9682156ae 100644 --- a/www/js/onboarding/OnboardingStack.tsx +++ b/www/js/onboarding/OnboardingStack.tsx @@ -12,8 +12,6 @@ import { displayErrorMsg } from '../plugin/logger'; const OnboardingStack = () => { const { onboardingState } = useContext(AppContext); - console.debug('onboardingState in OnboardingStack', onboardingState); - if (onboardingState.route == OnboardingRoute.WELCOME) { return ; } else if (onboardingState.route == OnboardingRoute.SUMMARY) { diff --git a/www/js/onboarding/WelcomePage.tsx b/www/js/onboarding/WelcomePage.tsx index 2cdd809f7..5699a47a3 100644 --- a/www/js/onboarding/WelcomePage.tsx +++ b/www/js/onboarding/WelcomePage.tsx @@ -59,10 +59,10 @@ const WelcomePage = () => { function scanCode() { window['cordova'].plugins.barcodeScanner.scan( (result) => { - console.debug('scanned code', result); + logDebug('scanCode: scanned ' + JSON.stringify(result)); let code = getCode(result); if (code != false) { - console.log('found code', code); + logDebug('scanCode: found code ' + code); loginWithToken(code); } else { displayError(result.text, 'invalid study reference'); @@ -83,7 +83,7 @@ const WelcomePage = () => { } }) .catch((err) => { - console.error('Error logging in with token', err); + displayError(err, 'Error logging in with token'); setExistingToken(''); }); } diff --git a/www/js/plugin/clientStats.ts b/www/js/plugin/clientStats.ts index f342439c1..bdf4c1888 100644 --- a/www/js/plugin/clientStats.ts +++ b/www/js/plugin/clientStats.ts @@ -1,4 +1,4 @@ -import { displayErrorMsg } from './logger'; +import { displayErrorMsg, logDebug } from './logger'; const CLIENT_TIME = 'stats/client_time'; const CLIENT_ERROR = 'stats/client_error'; @@ -40,6 +40,7 @@ async function getStatsEvent(name: string, reading: any) { export async function addStatReading(name: string, reading: any) { const db = window['cordova']?.plugins?.BEMUserCache; const event = await getStatsEvent(name, reading); + logDebug('addStatReading: adding CLIENT_TIME event: ' + JSON.stringify(event)); if (db) return db.putMessage(CLIENT_TIME, event); displayErrorMsg('addStatReading: db is not defined'); } @@ -47,6 +48,7 @@ export async function addStatReading(name: string, reading: any) { export async function addStatEvent(name: string) { const db = window['cordova']?.plugins?.BEMUserCache; const event = await getStatsEvent(name, null); + logDebug('addStatEvent: adding CLIENT_NAV_EVENT event: ' + JSON.stringify(event)); if (db) return db.putMessage(CLIENT_NAV_EVENT, event); displayErrorMsg('addStatEvent: db is not defined'); } @@ -54,6 +56,7 @@ export async function addStatEvent(name: string) { export async function addStatError(name: string, errorStr: string) { const db = window['cordova']?.plugins?.BEMUserCache; const event = await getStatsEvent(name, errorStr); + logDebug('addStatError: adding CLIENT_ERROR event: ' + JSON.stringify(event)); if (db) return db.putMessage(CLIENT_ERROR, event); displayErrorMsg('addStatError: db is not defined'); } diff --git a/www/js/plugin/logger.ts b/www/js/plugin/logger.ts index c2e678d40..98e852978 100644 --- a/www/js/plugin/logger.ts +++ b/www/js/plugin/logger.ts @@ -1,11 +1,11 @@ export const logDebug = (message: string) => - window['Logger'].log(window['Logger'].LEVEL_DEBUG, message); + window['Logger']?.log(window['Logger'].LEVEL_DEBUG, message); export const logInfo = (message: string) => - window['Logger'].log(window['Logger'].LEVEL_INFO, message); + window['Logger']?.log(window['Logger'].LEVEL_INFO, message); export const logWarn = (message: string) => - window['Logger'].log(window['Logger'].LEVEL_WARN, message); + window['Logger']?.log(window['Logger'].LEVEL_WARN, message); export function displayError(error: Error, title?: string) { const errorMsg = error.message ? error.message + '\n' + error.stack : JSON.stringify(error); diff --git a/www/js/plugin/storage.ts b/www/js/plugin/storage.ts index deed606b8..e22bb4669 100644 --- a/www/js/plugin/storage.ts +++ b/www/js/plugin/storage.ts @@ -83,10 +83,8 @@ function getUnifiedValue(key) { // both values are present, but they are different console.assert( ls_stored_val != null && uc_stored_val != null, - 'ls_stored_val =' + - JSON.stringify(ls_stored_val) + - 'uc_stored_val =' + - JSON.stringify(uc_stored_val), + `ls_stored_val = ${JSON.stringify(ls_stored_val)}; + uc_stored_val = ${JSON.stringify(uc_stored_val)}`, ); logWarn(`for key ${key}, uc_stored_val = ${JSON.stringify(uc_stored_val)}, ls_stored_val = ${JSON.stringify(ls_stored_val)}. @@ -145,25 +143,21 @@ function findMissing(fromKeys: any[], toKeys: any[]) { } export function storageSyncLocalAndNative() { - console.log('STORAGE_PLUGIN: Called syncAllWebAndNativeValues '); + logDebug('STORAGE_PLUGIN: Called syncAllWebAndNativeValues'); const syncKeys = window['cordova'].plugins.BEMUserCache.listAllLocalStorageKeys().then( (nativeKeys) => { - console.log('STORAGE_PLUGIN: native plugin returned'); const webKeys = Object.keys(localStorage); // I thought about iterating through the lists and copying over // only missing values, etc but `getUnifiedValue` already does // that, and we don't need to copy it // so let's just find all the missing values and read them - logDebug('STORAGE_PLUGIN: Comparing web keys ' + webKeys + ' with ' + nativeKeys); + logDebug(`STORAGE_PLUGIN: native keys returned = ${JSON.stringify(nativeKeys)}; + comparing against webKeys = ${JSON.stringify(webKeys)}`); let [foundNative, missingNative] = findMissing(webKeys, nativeKeys); let [foundWeb, missingWeb] = findMissing(nativeKeys, webKeys); - logDebug( - 'STORAGE_PLUGIN: Found native keys ' + - foundNative + - ' missing native keys ' + - missingNative, - ); - logDebug('STORAGE_PLUGIN: Found web keys ' + foundWeb + ' missing web keys ' + missingWeb); + logDebug(`STORAGE_PLUGIN: + Found native keys = ${foundNative}; Missing native keys = ${missingNative}; + Found web keys = ${foundWeb}; Missing web keys = ${missingWeb}`); const allMissing = missingNative.concat(missingWeb); logDebug('STORAGE_PLUGIN: Syncing all missing keys ' + allMissing); allMissing.forEach(getUnifiedValue); diff --git a/www/js/splash/customURL.ts b/www/js/splash/customURL.ts index ec3da45bd..21625ac29 100644 --- a/www/js/splash/customURL.ts +++ b/www/js/splash/customURL.ts @@ -1,3 +1,5 @@ +import { displayError } from '../plugin/logger'; + type UrlComponents = { [key: string]: string; }; @@ -16,7 +18,7 @@ export function onLaunchCustomURL( urlComponents[key] = value; } handler(url, urlComponents); - } catch { - console.log('not a valid url'); + } catch (err) { + displayError(err, 'onLaunchCustomURL: not a valid URL'); } } diff --git a/www/js/splash/notifScheduler.ts b/www/js/splash/notifScheduler.ts index f82d7b214..b6bc21778 100644 --- a/www/js/splash/notifScheduler.ts +++ b/www/js/splash/notifScheduler.ts @@ -66,9 +66,8 @@ function debugGetScheduled(prefix) { }; }); //have the list of scheduled show up in this log - logDebug( - `${prefix}, there are ${notifs.length} scheduled notifications at ${time} first is ${scheduledNotifs[0].key} at ${scheduledNotifs[0].val}`, - ); + logDebug(`${prefix}, there are ${notifs.length} scheduled notifications at ${time}; + first is ${scheduledNotifs[0].key} at ${scheduledNotifs[0].val}`); }); } @@ -79,12 +78,7 @@ export function getScheduledNotifs(isScheduling: boolean, scheduledPromise: Prom anywhere from 0-n of the scheduled notifs are displayed if actively scheduling, wait for the scheduledPromise to resolve before fetching prevents such errors */ - console.log('test log: isScheduling during getScheduledNotifs', isScheduling); - console.log('test log: scheduledPromise during getScheduledNotifs', scheduledPromise); if (isScheduling) { - console.log( - 'test log: requesting fetch while still actively scheduling, waiting on scheduledPromise', - ); logDebug('requesting fetch while still actively scheduling, waiting on scheduledPromise'); scheduledPromise.then(() => { getNotifs().then((notifs) => { @@ -92,7 +86,6 @@ export function getScheduledNotifs(isScheduling: boolean, scheduledPromise: Prom }); }); } else { - console.log('test log: not actively scheduling, fetching'); getNotifs().then((notifs) => { resolve(notifs); }); diff --git a/www/js/splash/remoteNotifyHandler.ts b/www/js/splash/remoteNotifyHandler.ts index 414f9f3f8..098625ee2 100644 --- a/www/js/splash/remoteNotifyHandler.ts +++ b/www/js/splash/remoteNotifyHandler.ts @@ -31,9 +31,7 @@ const launchWebpage = (url) => window['cordova'].InAppBrowser.open(url, '_blank' */ function onCloudNotifEvent(event) { const data = event.detail; - addStatEvent(statKeys.NOTIFICATION_OPEN).then(() => { - console.log('Added ' + statKeys.NOTIFICATION_OPEN + ' event. Data = ' + JSON.stringify(data)); - }); + addStatEvent(statKeys.NOTIFICATION_OPEN); logDebug('data = ' + JSON.stringify(data)); if ( data.additionalData && diff --git a/www/js/splash/startprefs.ts b/www/js/splash/startprefs.ts index 7700f315a..5e1edd188 100644 --- a/www/js/splash/startprefs.ts +++ b/www/js/splash/startprefs.ts @@ -69,7 +69,6 @@ export function readConsentState() { return fetch('json/startupConfig.json') .then((response) => response.json()) .then((startupConfigResult) => { - console.log(startupConfigResult); _req_consent = startupConfigResult.emSensorDataCollectionProtocol; logDebug('required consent version = ' + JSON.stringify(_req_consent)); return storageGet(DATA_COLLECTION_CONSENTED_PROTOCOL); diff --git a/www/js/splash/storeDeviceSettings.ts b/www/js/splash/storeDeviceSettings.ts index 8d0426ebb..a2a319ef5 100644 --- a/www/js/splash/storeDeviceSettings.ts +++ b/www/js/splash/storeDeviceSettings.ts @@ -36,17 +36,12 @@ function storeDeviceSettings() { * @param event that called this function */ function onConsentEvent(event) { - console.log( - 'got consented event ' + - JSON.stringify(event['name']) + - ' with data ' + - JSON.stringify(event.detail), - ); + logDebug(`got consented event ${JSON.stringify(event['name'])} + with data ${JSON.stringify(event.detail)}`); readIntroDone().then(async (isIntroDone) => { if (isIntroDone) { - logDebug( - 'intro is done -> reconsent situation, we already have a token -> store device settings', - ); + logDebug(`intro is done -> reconsent situation, + we already have a token -> store device settings`); await storeDeviceSettings(); } }); @@ -70,7 +65,7 @@ export function initStoreDeviceSettings() { readConsentState() .then(isConsented) .then(async (consentState) => { - console.log('found consent', consentState); + logDebug(`found consent: ${consentState}`); if (consentState == true) { await storeDeviceSettings(); } else { diff --git a/www/js/survey/enketo/AddNoteButton.tsx b/www/js/survey/enketo/AddNoteButton.tsx index f125f8185..93b3103b4 100644 --- a/www/js/survey/enketo/AddNoteButton.tsx +++ b/www/js/survey/enketo/AddNoteButton.tsx @@ -83,7 +83,7 @@ const AddNoteButton = ({ timelineEntry, notesConfig, storeKey }: Props) => { function launchAddNoteSurvey() { const surveyName = notesConfig.surveyName; - console.log('About to launch survey ', surveyName); + logDebug(`AddNoteButton: about to launch survey ${surveyName}`); setPrefillTimes(getPrefillTimes()); setModalVisible(true); } diff --git a/www/js/survey/enketo/AddedNotesList.tsx b/www/js/survey/enketo/AddedNotesList.tsx index e64783fe0..838300621 100644 --- a/www/js/survey/enketo/AddedNotesList.tsx +++ b/www/js/survey/enketo/AddedNotesList.tsx @@ -90,7 +90,7 @@ const AddedNotesList = ({ timelineEntry, additionEntries }: Props) => { function editEntry(entry) { setEditingEntry(entry); - console.debug('Editing entry is now ', entry); + logDebug('editingEntry = ' + JSON.stringify(entry)); setSurveyModalVisible(true); } diff --git a/www/js/survey/enketo/EnketoModal.tsx b/www/js/survey/enketo/EnketoModal.tsx index d1f11a83a..54a10ed7d 100644 --- a/www/js/survey/enketo/EnketoModal.tsx +++ b/www/js/survey/enketo/EnketoModal.tsx @@ -5,7 +5,7 @@ import { ModalProps } from 'react-native-paper'; import useAppConfig from '../../useAppConfig'; import { useTranslation } from 'react-i18next'; import { SurveyOptions, fetchSurvey, getInstanceStr, saveResponse } from './enketoHelper'; -import { displayError, displayErrorMsg } from '../../plugin/logger'; +import { displayError, displayErrorMsg, logDebug } from '../../plugin/logger'; type Props = Omit & { surveyName: string; @@ -40,9 +40,9 @@ const EnketoModal = ({ surveyName, onResponseSaved, opts, ...rest }: Props) => { // init logic: retrieve form -> inject into DOM -> initialize Enketo -> show modal function initSurvey() { - console.debug('Loading survey', surveyName); + logDebug('EnketoModal: loading survey ' + surveyName); const formPath = appConfig.survey_info?.surveys?.[surveyName]?.formPath; - if (!formPath) return console.error('No form path found for survey', surveyName); + if (!formPath) return displayErrorMsg('No form path found for survey ' + surveyName); fetchSurvey(formPath).then(({ form, model }) => { surveyJson.current = { form, model }; @@ -62,7 +62,7 @@ const EnketoModal = ({ surveyName, onResponseSaved, opts, ...rest }: Props) => { useEffect(() => { if (!rest.visible) return; - if (!appConfig) return console.error('App config not loaded yet'); + if (!appConfig) return displayErrorMsg('App config not loaded yet'); initSurvey(); }, [appConfig, rest.visible]); diff --git a/www/js/survey/inputMatcher.ts b/www/js/survey/inputMatcher.ts index b597400b8..f29926525 100644 --- a/www/js/survey/inputMatcher.ts +++ b/www/js/survey/inputMatcher.ts @@ -104,25 +104,23 @@ export function validUserInputForTimelineEntry( endChecks = true; // so we will just skip the end check } else { endChecks = userInput.data.end_ts <= nextEntryEnd; - logDebug( - `Second level of end checks when the next trip is defined(${userInput.data.end_ts} <= ${nextEntryEnd}) ${endChecks}`, - ); + logDebug(`Second level of end checks when the next trip is defined, + (${userInput.data.end_ts} <= ${nextEntryEnd}), + endChecks = ${endChecks}`); } } else { // next trip is not defined, last trip endChecks = userInput.data.end_local_dt?.day == userInput.data.start_local_dt?.day; logDebug('Second level of end checks for the last trip of the day'); - logDebug( - `compare ${userInput.data.end_local_dt?.day} with ${userInput.data.start_local_dt?.day} ${endChecks}`, - ); + logDebug(`compare ${userInput.data.end_local_dt?.day} with ${userInput.data.start_local_dt?.day}; + endChecks = ${endChecks}`); } if (endChecks) { // If we have flipped the values, check to see that there is sufficient overlap const overlapDuration = Math.min(userInput.data.end_ts, entryEnd) - Math.max(userInput.data.start_ts, entryStart); - logDebug( - `Flipped endCheck, overlap(${overlapDuration})/trip(${tlEntry.duration} (${overlapDuration} / ${tlEntry.duration})`, - ); + logDebug(`Flipped endCheck, overlapDuration / tlEntry.duration is + ${overlapDuration} / ${tlEntry.duration} = ${overlapDuration / tlEntry.duration}`); endChecks = overlapDuration / tlEntry.duration > 0.5; } } @@ -131,7 +129,7 @@ export function validUserInputForTimelineEntry( // parallels get_not_deleted_candidates() in trip_queries.py export function getNotDeletedCandidates(candidates: UserInputEntry[]): UserInputEntry[] { - console.log('getNotDeletedCandidates called with ' + candidates.length + ' candidates'); + logDebug('getNotDeletedCandidates called with ' + candidates.length + ' candidates'); // We want to retain all ACTIVE entries that have not been DELETED const allActiveList = candidates.filter((c) => !c.data.status || c.data.status == 'ACTIVE'); @@ -140,8 +138,9 @@ export function getNotDeletedCandidates(candidates: UserInputEntry[]): UserInput .map((c) => c.data['match_id']); const notDeletedActive = allActiveList.filter((c) => !allDeletedIds.includes(c.data['match_id'])); - console.log(`Found ${allActiveList.length} active entries, ${allDeletedIds.length} deleted entries -> - ${notDeletedActive.length} non deleted active entries`); + logDebug(`Found ${allActiveList.length} active entries; + ${allDeletedIds.length} deleted entries -> + ${notDeletedActive.length} non-deleted active entries`); return notDeletedActive; } @@ -157,7 +156,7 @@ export function getUserInputForTimelineEntry( return undefined; } - if (logsEnabled) console.log(`Input list = ${userInputList.map(printUserInput)}`); + if (logsEnabled) logDebug(`Input list = ${userInputList.map(printUserInput)}`); // undefined !== true, so this covers the label view case as well const potentialCandidates = userInputList.filter((ui) => @@ -171,11 +170,8 @@ export function getUserInputForTimelineEntry( } if (potentialCandidates.length === 1) { - logDebug( - `In getUserInputForTimelineEntry, one potential candidate, returning ${printUserInput( - potentialCandidates[0], - )}`, - ); + logDebug(`In getUserInputForTimelineEntry, one potential candidate, + returning ${printUserInput(potentialCandidates[0])}`); return potentialCandidates[0]; } @@ -209,7 +205,7 @@ export function getAdditionsForTimelineEntry( validUserInputForTimelineEntry(entry, nextEntry, ui, logsEnabled), ); - if (logsEnabled) console.log(`Matching Addition list ${matchingAdditions.map(printUserInput)}`); + if (logsEnabled) logDebug(`Matching Addition list ${matchingAdditions.map(printUserInput)}`); return matchingAdditions; } @@ -242,9 +238,8 @@ export function getUniqueEntries(combinedList) { `${JSON.stringify(existingVal)} vs ${JSON.stringify(e)}`, ); } else { - console.log( - `Found two entries with match_id ${existingVal.data.match_id} but they are identical`, - ); + logDebug(`Found two entries with match_id ${existingVal.data.match_id}, + but they are identical`); } } else { uniqueMap.set(e.data.match_id, e); diff --git a/www/js/survey/multilabel/confirmHelper.ts b/www/js/survey/multilabel/confirmHelper.ts index b2951ab98..cf61faa81 100644 --- a/www/js/survey/multilabel/confirmHelper.ts +++ b/www/js/survey/multilabel/confirmHelper.ts @@ -92,18 +92,12 @@ export function labelInputDetailsForTrip(userInputForTrip, appConfigParam?) { if (appConfigParam) appConfig = appConfigParam; if (appConfig.intro.mode_studied) { if (userInputForTrip?.['MODE']?.value == appConfig.intro.mode_studied) { - logDebug( - 'Found trip labeled with mode of study ' + - appConfig.intro.mode_studied + - '. Needs REPLACED_MODE', - ); + logDebug(`Found trip labeled with mode of study, ${appConfig.intro.mode_studied}. + Needs REPLACED_MODE`); return getLabelInputDetails(); } else { - logDebug( - 'Found trip not labeled with mode of study ' + - appConfig.intro.mode_studied + - ". Doesn't need REPLACED_MODE", - ); + logDebug(`Found trip not labeled with mode of study, ${appConfig.intro.mode_studied}. + Doesn't need REPLACED_MODE`); return baseLabelInputDetails; } } else { diff --git a/www/js/useAppStateChange.ts b/www/js/useAppStateChange.ts index 470eb67a6..9a77909a0 100644 --- a/www/js/useAppStateChange.ts +++ b/www/js/useAppStateChange.ts @@ -5,6 +5,7 @@ import { useEffect, useRef } from 'react'; import { AppState } from 'react-native'; +import { logDebug } from './plugin/logger'; const useAppStateChange = (onResume) => { const appState = useRef(AppState.currentState); @@ -16,7 +17,7 @@ const useAppStateChange = (onResume) => { } appState.current = nextAppState; - console.log('AppState', appState.current); + logDebug('new AppState: ' + appState.current); }); }, []); diff --git a/www/js/usePermissionStatus.ts b/www/js/usePermissionStatus.ts index c7fdacae4..8c3128bea 100644 --- a/www/js/usePermissionStatus.ts +++ b/www/js/usePermissionStatus.ts @@ -3,6 +3,7 @@ import useAppStateChange from './useAppStateChange'; import useAppConfig from './useAppConfig'; import { useTranslation } from 'react-i18next'; import { useAppTheme } from './appTheme'; +import { logDebug, logWarn } from './plugin/logger'; //refreshing checks with the plugins to update the check's statusState export function refreshAllChecks(checkList) { @@ -10,7 +11,7 @@ export function refreshAllChecks(checkList) { checkList.forEach((lc) => { lc.refresh(); }); - console.log('setting checks are', checkList); + logDebug('After refreshing all checks, checks are ' + JSON.stringify(checkList)); } type Check = { @@ -42,7 +43,7 @@ const usePermissionStatus = () => { let status = true; if (!checkList?.length) return undefined; // if checks not loaded yet, status is undetermined checkList.forEach((lc) => { - console.debug('check in permission status for ' + lc.name + ':', lc.statusState); + logDebug('check in permission status for ' + lc.name + ':' + lc.statusState); if (lc.statusState === false) { status = false; } @@ -67,33 +68,31 @@ const usePermissionStatus = () => { } async function checkOrFix(checkObj, nativeFn, showError = true) { - console.log('checking object', checkObj.name, checkObj); + logDebug('checking object ' + checkObj.name + ' ' + JSON.stringify(checkObj)); let newCheck = checkObj; return nativeFn() .then((status) => { - console.log('availability ', status); + logDebug('availability = ' + status); newCheck.statusState = true; updateCheck(newCheck); - console.log('after checking object', checkObj.name, checkList); + logDebug(`after checking obj ${checkObj.name}, checkList is ${JSON.stringify(checkList)}`); return status; }) .catch((error) => { - console.log('Error', error); if (showError) { - console.log('please fix again'); setError(error); setErrorVis(true); } newCheck.statusState = false; updateCheck(newCheck); - console.log('after checking object', checkObj.name, checkList); + logDebug(`after checking obj ${checkObj.name}, checkList is ${JSON.stringify(checkList)}`); return error; }); } function setupAndroidLocChecks() { let fixSettings = () => { - console.log('Fix and refresh location settings'); + logDebug('Fix and refresh location settings'); return checkOrFix( locSettingsCheck, window['cordova'].plugins.BEMDataCollection.fixLocationSettings, @@ -101,7 +100,7 @@ const usePermissionStatus = () => { ); }; let checkSettings = () => { - console.log('Refresh location settings'); + logDebug('Refresh location settings'); return checkOrFix( locSettingsCheck, window['cordova'].plugins.BEMDataCollection.isValidLocationSettings, @@ -109,7 +108,7 @@ const usePermissionStatus = () => { ); }; let fixPerms = () => { - console.log('fix and refresh location permissions'); + logDebug('fix and refresh location permissions'); return checkOrFix( locPermissionsCheck, window['cordova'].plugins.BEMDataCollection.fixLocationPermissions, @@ -121,7 +120,7 @@ const usePermissionStatus = () => { }); }; let checkPerms = () => { - console.log('fix and refresh location permissions'); + logDebug('fix and refresh location permissions'); return checkOrFix( locPermissionsCheck, window['cordova'].plugins.BEMDataCollection.isValidLocationPermissions, @@ -143,7 +142,7 @@ const usePermissionStatus = () => { : androidVersion < 12 ? 'intro.appstatus.locperms.description.android-11' : 'intro.appstatus.locperms.description.android-gte-12'; - console.log('description tags are ' + androidSettingsDescTag + ' ' + androidPermDescTag); + logDebug('description tags are ' + androidSettingsDescTag + ' ' + androidPermDescTag); // location settings let locSettingsCheck = { name: t('intro.appstatus.locsettings.name'), @@ -164,7 +163,7 @@ const usePermissionStatus = () => { function setupIOSLocChecks() { let fixSettings = () => { - console.log('Fix and refresh location settings'); + logDebug('Fix and refresh location settings'); return checkOrFix( locSettingsCheck, window['cordova'].plugins.BEMDataCollection.fixLocationSettings, @@ -172,7 +171,7 @@ const usePermissionStatus = () => { ); }; let checkSettings = () => { - console.log('Refresh location settings'); + logDebug('Refresh location settings'); return checkOrFix( locSettingsCheck, window['cordova'].plugins.BEMDataCollection.isValidLocationSettings, @@ -180,7 +179,7 @@ const usePermissionStatus = () => { ); }; let fixPerms = () => { - console.log('fix and refresh location permissions'); + logDebug('fix and refresh location permissions'); return checkOrFix( locPermissionsCheck, window['cordova'].plugins.BEMDataCollection.fixLocationPermissions, @@ -192,7 +191,7 @@ const usePermissionStatus = () => { }); }; let checkPerms = () => { - console.log('fix and refresh location permissions'); + logDebug('fix and refresh location permissions'); return checkOrFix( locPermissionsCheck, window['cordova'].plugins.BEMDataCollection.isValidLocationPermissions, @@ -205,7 +204,7 @@ const usePermissionStatus = () => { iOSVersion < 13 ? 'intro.appstatus.locperms.description.ios-lt-13' : 'intro.appstatus.locperms.description.ios-gte-13'; - console.log('description tags are ' + iOSSettingsDescTag + ' ' + iOSPermDescTag); + logDebug('description tags are ' + iOSSettingsDescTag + ' ' + iOSPermDescTag); const locSettingsCheck = { name: t('intro.appstatus.locsettings.name'), @@ -227,7 +226,7 @@ const usePermissionStatus = () => { function setupAndroidFitnessChecks() { if (window['device'].version.split('.')[0] >= 10) { let fixPerms = () => { - console.log('fix and refresh fitness permissions'); + logDebug('fix and refresh fitness permissions'); return checkOrFix( fitnessPermissionsCheck, window['cordova'].plugins.BEMDataCollection.fixFitnessPermissions, @@ -239,7 +238,7 @@ const usePermissionStatus = () => { }); }; let checkPerms = () => { - console.log('fix and refresh fitness permissions'); + logDebug('fix and refresh fitness permissions'); return checkOrFix( fitnessPermissionsCheck, window['cordova'].plugins.BEMDataCollection.isValidFitnessPermissions, @@ -261,7 +260,7 @@ const usePermissionStatus = () => { function setupIOSFitnessChecks() { let fixPerms = () => { - console.log('fix and refresh fitness permissions'); + logDebug('fix and refresh fitness permissions'); return checkOrFix( fitnessPermissionsCheck, window['cordova'].plugins.BEMDataCollection.fixFitnessPermissions, @@ -273,7 +272,7 @@ const usePermissionStatus = () => { }); }; let checkPerms = () => { - console.log('fix and refresh fitness permissions'); + logDebug('fix and refresh fitness permissions'); return checkOrFix( fitnessPermissionsCheck, window['cordova'].plugins.BEMDataCollection.isValidFitnessPermissions, @@ -294,7 +293,7 @@ const usePermissionStatus = () => { function setupAndroidNotificationChecks() { let fixPerms = () => { - console.log('fix and refresh notification permissions'); + logDebug('fix and refresh notification permissions'); return checkOrFix( appAndChannelNotificationsCheck, window['cordova'].plugins.BEMDataCollection.fixShowNotifications, @@ -302,7 +301,7 @@ const usePermissionStatus = () => { ); }; let checkPerms = () => { - console.log('fix and refresh notification permissions'); + logDebug('fix and refresh notification permissions'); return checkOrFix( appAndChannelNotificationsCheck, window['cordova'].plugins.BEMDataCollection.isValidShowNotifications, @@ -322,7 +321,7 @@ const usePermissionStatus = () => { function setupAndroidBackgroundRestrictionChecks() { let fixPerms = () => { - console.log('fix and refresh backgroundRestriction permissions'); + logDebug('fix and refresh backgroundRestriction permissions'); return checkOrFix( unusedAppsUnrestrictedCheck, window['cordova'].plugins.BEMDataCollection.fixUnusedAppRestrictions, @@ -330,7 +329,7 @@ const usePermissionStatus = () => { ); }; let checkPerms = () => { - console.log('fix and refresh backgroundRestriction permissions'); + logDebug('fix and refresh backgroundRestriction permissions'); return checkOrFix( unusedAppsUnrestrictedCheck, window['cordova'].plugins.BEMDataCollection.isUnusedAppUnrestricted, @@ -338,7 +337,7 @@ const usePermissionStatus = () => { ); }; let fixBatteryOpt = () => { - console.log('fix and refresh battery optimization permissions'); + logDebug('fix and refresh battery optimization permissions'); return checkOrFix( ignoreBatteryOptCheck, window['cordova'].plugins.BEMDataCollection.fixIgnoreBatteryOptimizations, @@ -346,7 +345,7 @@ const usePermissionStatus = () => { ); }; let checkBatteryOpt = () => { - console.log('fix and refresh battery optimization permissions'); + logDebug('fix and refresh battery optimization permissions'); return checkOrFix( ignoreBatteryOptCheck, window['cordova'].plugins.BEMDataCollection.isIgnoreBatteryOptimizations, @@ -403,7 +402,7 @@ const usePermissionStatus = () => { //TODO - update samsung handling based on feedback - console.log('Explanation = ' + explanationList); + logDebug('Explanation = ' + explanationList); } function createChecklist() { @@ -419,14 +418,14 @@ const usePermissionStatus = () => { } else { setError('Alert! unknownplatform, no tracking'); setErrorVis(true); - console.log('Alert! unknownplatform, no tracking'); //need an alert, can use AlertBar? + logWarn('Alert! unknownplatform, no tracking'); //need an alert, can use AlertBar? } refreshAllChecks(checkList); } useAppStateChange(() => { - console.log('PERMISSION CHECK: app has resumed, should refresh'); + logDebug('PERMISSION CHECK: app has resumed, should refresh'); refreshAllChecks(checkList); }); @@ -435,7 +434,7 @@ const usePermissionStatus = () => { if (appConfig && window['device']?.platform) { setupPermissionText(); setHaveSetText(true); - console.log('setting up permissions'); + logDebug('setting up permissions'); createChecklist(); } }, [appConfig]);