Skip to content

Commit

Permalink
Logging levels
Browse files Browse the repository at this point in the history
  • Loading branch information
rhit-villencr committed Feb 4, 2025
1 parent d1d45c3 commit c043dbe
Show file tree
Hide file tree
Showing 9 changed files with 38 additions and 37 deletions.
2 changes: 1 addition & 1 deletion app/accountSetting.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export default function AccountSetting() {
if (response.status == 401) {
throw new Error(response.data.message);
}
cLog('Data saved successfully:', formData);
cLog(1, 'Data saved successfully:', formData);
} catch (error) {
console.error('Error saving data:', error);
}
Expand Down
22 changes: 11 additions & 11 deletions app/genericAddViewEventPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,18 +19,18 @@ const GenericAddViewPageForm: React.FC<GenericEventPageProps> = ({ title, initia
const [showCancelModal, setShowCancelModal] = useState(false);

const route = useRoute<RouteProp<RootStackParamList, any>>();
cLog({ "Recieved Route": route });
cLog(1,{ "Recieved Route": route });
const navigation = useNavigation<StackNavigationProp<RootStackParamList>>();
let event = initialData.event ? initialData.event : initialData;
cLog({ "Initial Data": initialData });
cLog(1, { "Initial Data": initialData });
if (route.params) event = route.params?.event.event;
cLog({ "Event": event });
cLog(1, { "Event": event });
const [formData, setFormData] = useState({
...event,
event_date: event.event_date ? new Date(event.event_date) : new Date(),
event_time: event.event_time ? new Date(`1970-01-01T${event.event_time}`) : new Date(),
});
cLog({ "Form Data": formData });
cLog(1, { "Form Data": formData });

const handleSave = async () => {
const formattedData = {
Expand All @@ -41,12 +41,12 @@ const GenericAddViewPageForm: React.FC<GenericEventPageProps> = ({ title, initia
repeat_timeline: formData.repeat_timeline,
ingredients: formData.ingredients?.join(',')
};
cLog(formattedData);
cLog(1, formattedData);
try {
const token = await AsyncStorage.getItem('token');
cLog('Saving event to:' + updateEndpoint);
cLog(1, 'Saving event to:' + updateEndpoint);
const response = await call(`${updateEndpoint}/${token}`, method, undefined, formattedData)
cLog('Event updated successfully:' + response.data);
cLog(1, 'Event updated successfully:' + response.data);
} catch (error) {
console.error('Error saving event:', error);
}
Expand Down Expand Up @@ -84,7 +84,7 @@ const GenericAddViewPageForm: React.FC<GenericEventPageProps> = ({ title, initia
useFocusEffect(
useCallback(() => {
const fetchData = async () => {
cLog('Fetching additional data...');
cLog(1, 'Fetching additional data...');
try {
const token = await AsyncStorage.getItem('token');
const response = await call(`${fetchEndpoint}/${token}`, 'GET');
Expand All @@ -97,15 +97,15 @@ const GenericAddViewPageForm: React.FC<GenericEventPageProps> = ({ title, initia
setTimeout(() => {
setAdditionalData(formattedData);
}, 100);
cLog('Fetched and formatted data:', formattedData);
cLog(1, 'Fetched and formatted data:', formattedData);
} catch (error) {
console.error('Error fetching additional data:', error);
}
};
const verifyLoginStatus = async () => {
const [isLoggedIn, token] = await AsyncStorage.multiGet(['isLoggedIn', 'token']);
if (isLoggedIn[1] === 'true' && token[1]) {
cLog(`User is logged in with Token: ${token[1]}`);
cLog(1, `User is logged in with Token: ${token[1]}`);
}
};

Expand All @@ -115,7 +115,7 @@ const GenericAddViewPageForm: React.FC<GenericEventPageProps> = ({ title, initia
}, [])
);
useEffect(() => {
cLog('Updated Additional Data:', additionalData);
cLog(1, 'Updated Additional Data:', additionalData);
}, [additionalData]);

const renderField = (field: any) => {
Expand Down
10 changes: 5 additions & 5 deletions app/genericMainPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,11 @@ const GenericMainPageForm: React.FC<FormProps> = ({

const handleViewPress = (item: Task) => {
const route = { ...item, thisPage };
cLog({ "Pre-Route": route });
cLog(1, { "Pre-Route": route });
if (route.thisPage === 'mainPage') {
route.thisPage = getPageFromEventType(route.event.event_type) as keyof RootStackParamList;
}
cLog({ "Route": route });
cLog(1, { "Route": route });
navigation.navigate(getPageName(route.thisPage) as any, { event: route });
}

Expand All @@ -77,7 +77,7 @@ const GenericMainPageForm: React.FC<FormProps> = ({
const fetchEvents = async () => {
try {
const token = await AsyncStorage.getItem('token');
cLog(token)
cLog(1, token)
const response = await call(`${hitAddress}${token}`, 'GET');

if (response.status === 200 && response.data) {
Expand All @@ -86,7 +86,7 @@ const GenericMainPageForm: React.FC<FormProps> = ({
setIsGoogleCalendarLinked(googleCalendarLinked);
}
const eventsArray = Array.isArray(events) ? events : response.data;
cLog({ 'eventsArray': eventsArray });
cLog(1, { 'eventsArray': eventsArray });
const formattedEvents = eventsArray.map((event: any) => ({
id: eventIdFunc(event),
title: eventTitleFunc(event),
Expand All @@ -109,7 +109,7 @@ const GenericMainPageForm: React.FC<FormProps> = ({
const verifyLoginStatus = async () => {
const [isLoggedIn, token] = await AsyncStorage.multiGet(['isLoggedIn', 'token']);
if (isLoggedIn[1] === 'true' && token[1]) {
cLog(`User is logged in with Token: ${token[1]}`);
cLog(1, `User is logged in with Token: ${token[1]}`);
}
};

Expand Down
8 changes: 4 additions & 4 deletions app/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export default function AuthScreen() {

try {
const response = await call(url, 'POST', undefined, { username, password });
cLog("Response:", response);
cLog(1, "Response:", response);
if (response.status == 401) {
throw new Error(response.data.message);
}
Expand Down Expand Up @@ -60,7 +60,7 @@ export default function AuthScreen() {
iosClientId: process.env.EXPO_PUBLIC_IOS_CLIENT_ID,
androidClientId: process.env.EXPO_PUBLIC_ANDROID_CLIENT_ID,
});
// cLog("Request:", request);
cLog(3, "Request:", request);

useEffect(() => {
if (response?.type === 'success') {
Expand Down Expand Up @@ -95,9 +95,9 @@ export default function AuthScreen() {

const verifyLoginStatus = async () => {
const [isLoggedIn, token] = await AsyncStorage.multiGet(['isLoggedIn', 'token']);
cLog(token)
cLog(1, token)
if (isLoggedIn[1] === 'true' && token[1]) {
cLog(`User is logged in with Token: ${token[1]}`);
cLog(1, `User is logged in with Token: ${token[1]}`);
navigation.navigate('mainPage');
}
};
Expand Down
14 changes: 7 additions & 7 deletions app/mainCalendarEvents.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,15 @@ export default function CalendarTracker() {

const handlePress = async () => {
try {
cLog("Initiating OAuth login...");
cLog(1, "Initiating OAuth login...");
const authUrl = `${AUTH_URI}?response_type=code&client_id=${CLIENT_ID}&redirect_uri=${encodeURIComponent(REDIRECT_URI)}&scope=https://www.googleapis.com/auth/calendar&access_type=offline&prompt=consent`;
const result = await WebBrowser.openAuthSessionAsync(authUrl, REDIRECT_URI);
cLog("WebBrowser result:" + result);
cLog(1, "WebBrowser result:" + result);
if (result.type === 'success' && result.url) {
const authCodeMatch = result.url.match(/code=([^&]*)/);
const authCode = authCodeMatch ? authCodeMatch[1] : null;
if (authCode) {
cLog("Received authorization code:" + authCode);
cLog(1, "Received authorization code:" + authCode);
getAccessToken(authCode);
} else {
console.error("Authorization code not found in the redirect URL");
Expand All @@ -44,7 +44,7 @@ export default function CalendarTracker() {
};

const getAccessToken = async (authCode: string) => {
cLog("Exchanging authorization code for access token...");
cLog(1, "Exchanging authorization code for access token...");
try {
const params = new URLSearchParams();
params.append('code', authCode);
Expand All @@ -54,7 +54,7 @@ export default function CalendarTracker() {
params.append('grant_type', 'authorization_code');
const response = await full_call(TOKEN_URI, 'POST', 'application/x-www-form-urlencoded', params);
if (response.data.access_token) {
cLog("Received access token:" + response.data.access_token);
cLog(1, "Received access token:" + response.data.access_token);
linkGoogleCalendar(response.data.access_token);
} else {
console.error("Failed to retrieve access token");
Expand All @@ -67,12 +67,12 @@ export default function CalendarTracker() {
};

const linkGoogleCalendar = async (accessToken: any) => {
cLog("Linking Google Calendar for user and fetching events...");
cLog(1, "Linking Google Calendar for user and fetching events...");
try {
const token = await AsyncStorage.getItem('token');
const response = await call(`/link_calendar/${token}`, 'POST', undefined, { accessToken: accessToken });
if (response.status === 200 && response.data.includes("successfully")) {
cLog('Google Calendar linked successfully:' + response.data);
cLog(1, 'Google Calendar linked successfully:' + response.data);
Alert.alert('Google Calendar linked successfully!');
setIsGoogleCalendarLinked(true);
} else {
Expand Down
4 changes: 2 additions & 2 deletions app/mainPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ export default function TaskScreen() {
const verifyLoginStatus = async () => {
const [isLoggedIn, storedToken] = await AsyncStorage.multiGet(['isLoggedIn', 'token']);
if (isLoggedIn[1] === 'true' && storedToken[1]) {
cLog(`User is logged in with Token: ${storedToken[1]}`);
cLog(1, `User is logged in with Token: ${storedToken[1]}`);
} else {
cLog('User is not logged in');
cLog(1, 'User is not logged in');
}
};
const initializeHeader = async () => {
Expand Down
4 changes: 2 additions & 2 deletions app/notes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export default function Notes() {
event_time: currentTime,
};
const response = await call(`/add_note/${token}`, 'PUT', undefined, updatedFormData);
cLog('Note saved successfully: ' + response.data);
cLog(1, 'Note saved successfully: ' + response.data);
} catch (error) {
console.error('Error saving note:', error);
}
Expand All @@ -35,7 +35,7 @@ export default function Notes() {
try {
const token = await AsyncStorage.getItem('token');
const hit = '/get_note/' + token;
cLog('Fetching note from: ' + hit);
cLog(1, 'Fetching note from: ' + hit);

const response = await call(hit, 'GET');
const events = response.data.map((event: { text: any; }) => ({
Expand Down
4 changes: 2 additions & 2 deletions components/apiCall.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { cLog } from './log';

export const call = async (endpoint: string, method: string, headers?: string, data?: any): Promise<AxiosResponse<any>> => {
const fullUrl = `${IPAddr}${endpoint}`;
cLog('API Call URL:', fullUrl);
cLog(1, 'API Call URL:', fullUrl);

try {
const response = await axios({
Expand All @@ -21,7 +21,7 @@ export const call = async (endpoint: string, method: string, headers?: string, d
};

export const full_call = async (endpoint: string, method: string, headers?: string, data?: any): Promise<AxiosResponse<any>> => {
cLog('API Call URL:', endpoint);
cLog(1, 'API Call URL:', endpoint);

try {
const response = await axios({
Expand Down
7 changes: 4 additions & 3 deletions components/log.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
const logging = true;
const loggingLevel = 2;

interface LogFunction {
(...messages: any[]): void;
(logLevel?: number, ...messages: any[]): void;
}

export const cLog: LogFunction = (...messages) => {
if (logging) {
export const cLog: LogFunction = (logLevel = 0, ...messages) => {
if (logging && logLevel <= loggingLevel) {
console.log(...messages);
}
};

0 comments on commit c043dbe

Please sign in to comment.