From 579ed6de7c9729a9d345c6dbd68977a719c49ff7 Mon Sep 17 00:00:00 2001 From: MartinBraquet Date: Sun, 1 Mar 2026 04:05:14 +0100 Subject: [PATCH] Use logger debug --- backend/api/src/create-profile.ts | 5 +- backend/api/src/delete-me.ts | 3 +- backend/api/src/get-messages-count.ts | 3 +- backend/api/src/get-profiles.ts | 3 +- backend/api/src/helpers/private-messages.ts | 5 +- backend/api/src/send-search-notifications.ts | 11 ++-- backend/api/src/test.ts | 3 +- backend/email/emails/functions/send-email.ts | 7 ++- .../email/emails/functions/send-test-email.ts | 6 +- backend/scripts/find-tiptap-nodes.ts | 33 +++++----- backend/scripts/regen-schema.ts | 13 ++-- backend/scripts/remove-tiptap-nodes.ts | 21 ++++--- backend/scripts/run-script.ts | 9 +-- backend/shared/src/firebase-utils.ts | 5 +- .../generate-and-update-avatar-urls.ts | 3 +- backend/shared/src/helpers/search.ts | 4 +- backend/shared/src/init-admin.ts | 7 ++- common/src/envs/constants.ts | 10 +-- common/src/geodb.ts | 5 +- {web/lib => common/src}/logger.ts | 30 ++++++--- common/src/logging.ts | 62 ------------------- common/src/profiles/constants.ts | 4 +- common/src/secrets.ts | 3 +- common/src/util/matrix.ts | 5 +- web/components/SEO.tsx | 4 +- .../add-compatibility-question-button.tsx | 5 +- web/components/filters/use-filters.ts | 4 +- web/components/optional-profile-form.tsx | 5 +- web/components/profile/profile-header.tsx | 3 +- web/components/profile/profile-info.tsx | 3 +- web/components/profiles/profiles-home.tsx | 3 +- web/components/site-logo.tsx | 4 +- web/components/votes/vote-info.tsx | 3 +- web/hooks/use-nearby-locations.ts | 3 +- web/hooks/use-profile.ts | 5 +- web/hooks/use-user.ts | 3 +- web/lib/api.ts | 5 +- web/lib/firebase/google-onetap-login.tsx | 3 +- web/pages/[username]/index.tsx | 19 +++--- web/pages/index.tsx | 3 +- web/pages/register.tsx | 3 +- web/pages/signin.tsx | 8 +-- web/pages/signup.tsx | 3 +- web/tests/unit/logger.test.ts | 2 +- 44 files changed, 169 insertions(+), 182 deletions(-) rename {web/lib => common/src}/logger.ts (83%) delete mode 100644 common/src/logging.ts diff --git a/backend/api/src/create-profile.ts b/backend/api/src/create-profile.ts index c13ec6bf..834de9f3 100644 --- a/backend/api/src/create-profile.ts +++ b/backend/api/src/create-profile.ts @@ -1,5 +1,6 @@ import {APIError, APIHandler} from 'api/helpers/endpoint' import {sendDiscordMessage} from 'common/discord/core' +import {debug} from 'common/logger' import {jsonToMarkdown} from 'common/md' import {trimStrings} from 'common/parsing' import {HOUR_MS, MINUTE_MS, sleep} from 'common/util/time' @@ -31,7 +32,7 @@ export const createProfile: APIHandler<'create-profile'> = async (body, auth) => updateUser(pg, auth.uid, {avatarUrl: body.pinned_url}) } - console.debug('body', body) + debug('body', body) const {data, error} = await tryCatch(insert(pg, 'profiles', {user_id: auth.uid, ...body})) @@ -73,7 +74,7 @@ export const createProfile: APIHandler<'create-profile'> = async (body, auth) => n % 50 === 0 ) } - console.debug(nProfiles, isMilestone(nProfiles)) + debug(nProfiles, isMilestone(nProfiles)) if (isMilestone(nProfiles)) { await sendDiscordMessage(`We just reached **${nProfiles}** total profiles! 🎉`, 'general') } diff --git a/backend/api/src/delete-me.ts b/backend/api/src/delete-me.ts index 2ad883e3..46ce2e7e 100644 --- a/backend/api/src/delete-me.ts +++ b/backend/api/src/delete-me.ts @@ -1,3 +1,4 @@ +import {debug} from 'common/logger' import * as admin from 'firebase-admin' import {deleteUserFiles} from 'shared/firebase-utils' import {createSupabaseDirectClient} from 'shared/supabase/init' @@ -42,7 +43,7 @@ export const deleteMe: APIHandler<'me/delete'> = async ({reasonCategory, reasonD try { const auth = admin.auth() await auth.deleteUser(userId) - console.debug(`Deleted user ${userId} from Firebase Auth and Supabase`) + debug(`Deleted user ${userId} from Firebase Auth and Supabase`) } catch (e) { console.error('Error deleting user from Firebase Auth:', e) } diff --git a/backend/api/src/get-messages-count.ts b/backend/api/src/get-messages-count.ts index e27f1daa..c086f5aa 100644 --- a/backend/api/src/get-messages-count.ts +++ b/backend/api/src/get-messages-count.ts @@ -1,3 +1,4 @@ +import {debug} from 'common/logger' import {createSupabaseDirectClient} from 'shared/supabase/init' import {APIHandler} from './helpers/endpoint' @@ -12,7 +13,7 @@ export const getMessagesCount: APIHandler<'get-messages-count'> = async (_, _aut [], ) const count = Number(result.count) - console.debug('private_user_messages count:', count) + debug('private_user_messages count:', count) return { count: count, } diff --git a/backend/api/src/get-profiles.ts b/backend/api/src/get-profiles.ts index a9c9b432..63a77e14 100644 --- a/backend/api/src/get-profiles.ts +++ b/backend/api/src/get-profiles.ts @@ -1,4 +1,5 @@ import {type APIHandler} from 'api/helpers/endpoint' +import {debug} from 'common/logger' import {OptionTableKey} from 'common/profiles/constants' import {compact} from 'lodash' import {convertRow} from 'shared/profiles/supabase' @@ -69,7 +70,7 @@ export type profileQueryType = { export const loadProfiles = async (props: profileQueryType) => { const pg = createSupabaseDirectClient() - console.debug('loadProfiles', props) + debug('loadProfiles', props) const { limit: limitParam, after, diff --git a/backend/api/src/helpers/private-messages.ts b/backend/api/src/helpers/private-messages.ts index 7150734e..37bc0ded 100644 --- a/backend/api/src/helpers/private-messages.ts +++ b/backend/api/src/helpers/private-messages.ts @@ -1,6 +1,7 @@ import {type JSONContent} from '@tiptap/core' import {APIError} from 'common/api/utils' import {ChatVisibility} from 'common/chat-message' +import {debug} from 'common/logger' import {Json} from 'common/supabase/schema' import {User} from 'common/user' import {parseJsonContentToText} from 'common/util/parse' @@ -174,7 +175,7 @@ const notifyOtherUserInChannelIfInactive = async ( // TODO: notification only for active user const receiver = await getUser(receiverId) - console.debug('receiver:', receiver) + debug('receiver:', receiver) if (!receiver) return // Push notifs @@ -212,7 +213,7 @@ const notifyOtherUserInChannelIfInactive = async ( const createNewMessageNotification = async (fromUser: User, toUser: User, channelId: number) => { const privateUser = await getPrivateUser(toUser.id) - console.debug('privateUser:', privateUser) + debug('privateUser:', privateUser) if (!privateUser) return await sendNewMessageEmail(privateUser, fromUser, toUser, channelId) } diff --git a/backend/api/src/send-search-notifications.ts b/backend/api/src/send-search-notifications.ts index 3451d75a..b1d0c104 100644 --- a/backend/api/src/send-search-notifications.ts +++ b/backend/api/src/send-search-notifications.ts @@ -1,4 +1,5 @@ import {loadProfiles, profileQueryType} from 'api/get-profiles' +import {debug} from 'common/logger' import {MatchesByUserType} from 'common/profiles/bookmarked_searches' import {Row} from 'common/supabase/utils' import {sendSearchAlertsEmail} from 'email/functions/helpers' @@ -25,7 +26,7 @@ export const sendSearchNotifications = async () => { [], convertSearchRow, )) as Row<'bookmarked_searches'>[] - console.debug(`Running ${searches.length} bookmarked searches`) + debug(`Running ${searches.length} bookmarked searches`) const _users = (await pg.map( renderSql(select('users.*'), from('users')), @@ -33,7 +34,7 @@ export const sendSearchNotifications = async () => { convertSearchRow, )) as Row<'users'>[] const users = keyBy(_users, 'id') - console.debug('users', users) + debug('users', users) const _privateUsers = (await pg.map( renderSql(select('private_users.*'), from('private_users')), @@ -41,7 +42,7 @@ export const sendSearchNotifications = async () => { convertSearchRow, )) as Row<'private_users'>[] const privateUsers = keyBy(_privateUsers, 'id') - console.debug('privateUsers', privateUsers) + debug('privateUsers', privateUsers) const matches: MatchesByUserType = {} @@ -56,7 +57,7 @@ export const sendSearchNotifications = async () => { shortBio: true, } const {profiles} = await loadProfiles(props as profileQueryType) - console.debug(profiles.map((item: any) => item.name)) + debug(profiles.map((item: any) => item.name)) if (!profiles.length) continue if (!(row.creator_id in matches)) { if (!privateUsers[row.creator_id]) continue @@ -75,7 +76,7 @@ export const sendSearchNotifications = async () => { })), }) } - console.debug('matches:', JSON.stringify(matches, null, 2)) + debug('matches:', JSON.stringify(matches, null, 2)) await notifyBookmarkedSearch(matches) return {status: 'success'} diff --git a/backend/api/src/test.ts b/backend/api/src/test.ts index 746f4766..1de7e039 100644 --- a/backend/api/src/test.ts +++ b/backend/api/src/test.ts @@ -1,8 +1,9 @@ +import {debug} from 'common/logger' import {sendTestEmail} from 'email/functions/helpers' export const localSendTestEmail = async () => { sendTestEmail('hello@compassmeet.com') - .then(() => console.debug('Email sent successfully!')) + .then(() => debug('Email sent successfully!')) .catch((error) => console.error('Failed to send email:', error)) return {message: 'Email sent successfully!'} } diff --git a/backend/email/emails/functions/send-email.ts b/backend/email/emails/functions/send-email.ts index 1a85c6f0..ee8b7022 100644 --- a/backend/email/emails/functions/send-email.ts +++ b/backend/email/emails/functions/send-email.ts @@ -1,4 +1,5 @@ import {IS_LOCAL} from 'common/hosting/constants' +import {debug} from 'common/logger' import {sleep} from 'common/util/time' import {type CreateEmailOptions, CreateEmailRequestOptions, Resend} from 'resend' import {log} from 'shared/utils' @@ -11,7 +12,7 @@ export const sendEmail = async ( options?: CreateEmailRequestOptions, ) => { const resend = getResend() - console.debug(resend, payload, options) + debug(resend, payload, options) const skip = IS_LOCAL if (skip) { @@ -25,7 +26,7 @@ export const sendEmail = async ( {replyTo: 'Compass ', ...payload}, options, ) - console.debug('resend.emails.send', data, error) + debug('resend.emails.send', data, error) if (error) { log.error(`Failed to send email to ${payload.to} with subject ${payload.subject}`) @@ -45,7 +46,7 @@ const getResend = () => { if (resend) return resend if (!process.env.RESEND_KEY) { - console.debug('No RESEND_KEY, skipping email send') + debug('No RESEND_KEY, skipping email send') return } diff --git a/backend/email/emails/functions/send-test-email.ts b/backend/email/emails/functions/send-test-email.ts index 14983bc5..104b1452 100755 --- a/backend/email/emails/functions/send-test-email.ts +++ b/backend/email/emails/functions/send-test-email.ts @@ -1,14 +1,16 @@ +import {debug} from 'common/logger' + import {sendTestEmail} from './helpers' if (require.main === module) { const email = process.argv[2] if (!email) { console.error('Please provide an email address') - console.debug('Usage: ts-node send-test-email.ts your@email.com') + debug('Usage: ts-node send-test-email.ts your@email.com') process.exit(1) } sendTestEmail(email) - .then(() => console.debug('Email sent successfully!')) + .then(() => debug('Email sent successfully!')) .catch((error) => console.error('Failed to send email:', error)) } diff --git a/backend/scripts/find-tiptap-nodes.ts b/backend/scripts/find-tiptap-nodes.ts index 0cead3f4..7ff1900d 100644 --- a/backend/scripts/find-tiptap-nodes.ts +++ b/backend/scripts/find-tiptap-nodes.ts @@ -1,6 +1,7 @@ import {runScript} from './run-script' import {from, renderSql, select, where} from 'shared/supabase/sql-builder' import {SupabaseDirectClient} from 'shared/supabase/init' +import {debug} from 'common/logger' runScript(async ({pg}) => { const tests = [ @@ -19,7 +20,7 @@ runScript(async ({pg}) => { }) const getNodes = async (pg: SupabaseDirectClient, nodeName: string) => { - console.debug(`\nSearching comments for ${nodeName}...`) + debug(`\nSearching comments for ${nodeName}...`) const commentQuery = renderSql( select('id, user_id, on_user_id, content'), from('profile_comments'), @@ -27,15 +28,15 @@ const getNodes = async (pg: SupabaseDirectClient, nodeName: string) => { ) const comments = await pg.manyOrNone(commentQuery) - console.debug(`Found ${comments.length} comments:`) + debug(`Found ${comments.length} comments:`) comments.forEach((comment) => { - console.debug('\nComment ID:', comment.id) - console.debug('From user:', comment.user_id) - console.debug('On user:', comment.on_user_id) - console.debug('Content:', JSON.stringify(comment.content)) + debug('\nComment ID:', comment.id) + debug('From user:', comment.user_id) + debug('On user:', comment.on_user_id) + debug('Content:', JSON.stringify(comment.content)) }) - console.debug(`\nSearching private messages for ${nodeName}...`) + debug(`\nSearching private messages for ${nodeName}...`) const messageQuery = renderSql( select('id, user_id, channel_id, content'), from('private_user_messages'), @@ -43,15 +44,15 @@ const getNodes = async (pg: SupabaseDirectClient, nodeName: string) => { ) const messages = await pg.manyOrNone(messageQuery) - console.debug(`Found ${messages.length} private messages:`) + debug(`Found ${messages.length} private messages:`) messages.forEach((msg) => { - console.debug('\nMessage ID:', msg.id) - console.debug('From user:', msg.user_id) - console.debug('Channel:', msg.channel_id) - console.debug('Content:', JSON.stringify(msg.content)) + debug('\nMessage ID:', msg.id) + debug('From user:', msg.user_id) + debug('Channel:', msg.channel_id) + debug('Content:', JSON.stringify(msg.content)) }) - console.debug(`\nSearching profiles for ${nodeName}...`) + debug(`\nSearching profiles for ${nodeName}...`) const users = renderSql( select('user_id, bio'), from('profiles'), @@ -59,9 +60,9 @@ const getNodes = async (pg: SupabaseDirectClient, nodeName: string) => { ) const usersWithMentions = await pg.manyOrNone(users) - console.debug(`Found ${usersWithMentions.length} users:`) + debug(`Found ${usersWithMentions.length} users:`) usersWithMentions.forEach((user) => { - console.debug('\nUser ID:', user.user_id) - console.debug('Bio:', JSON.stringify(user.bio)) + debug('\nUser ID:', user.user_id) + debug('Bio:', JSON.stringify(user.bio)) }) } diff --git a/backend/scripts/regen-schema.ts b/backend/scripts/regen-schema.ts index b7e0fefc..0465e776 100644 --- a/backend/scripts/regen-schema.ts +++ b/backend/scripts/regen-schema.ts @@ -2,6 +2,7 @@ import * as fs from 'fs/promises' import {execSync} from 'child_process' import {type SupabaseDirectClient} from 'shared/supabase/init' import {runScript} from 'run-script' +import {debug} from 'common/logger' const outputDir = `../supabase/` @@ -176,7 +177,7 @@ async function getTableInfo(pg: SupabaseDirectClient, tableName: string) { } async function getFunctions(pg: SupabaseDirectClient) { - console.debug('Getting functions') + debug('Getting functions') const rows = await pg.manyOrNone<{ function_name: string definition: string @@ -194,7 +195,7 @@ async function getFunctions(pg: SupabaseDirectClient) { } async function getViews(pg: SupabaseDirectClient) { - console.debug('Getting views') + debug('Getting views') return pg.manyOrNone<{view_name: string; definition: string}>( `SELECT table_name AS view_name, @@ -212,7 +213,7 @@ async function generateSQLFiles(pg: SupabaseDirectClient) { (row) => row.tablename as string, ) - console.debug(`Getting info for ${tables.length} tables`) + debug(`Getting info for ${tables.length} tables`) const tableInfos = await Promise.all(tables.map((table) => getTableInfo(pg, table))) const functions = await getFunctions(pg) const views = await getViews(pg) @@ -324,7 +325,7 @@ async function generateSQLFiles(pg: SupabaseDirectClient) { await fs.writeFile(`${outputDir}/${tableInfo.tableName}.sql`, content) } - console.debug('Writing remaining functions to functions.sql') + debug('Writing remaining functions to functions.sql') let functionsContent = `-- This file is autogenerated from regen-schema.ts\n\n` for (const func of functions) { @@ -333,7 +334,7 @@ async function generateSQLFiles(pg: SupabaseDirectClient) { await fs.writeFile(`${outputDir}/functions.sql`, functionsContent) - console.debug('Writing views to views.sql') + debug('Writing views to views.sql') let viewsContent = `-- This file is autogenerated from regen-schema.ts\n\n` for (const view of views) { @@ -343,6 +344,6 @@ async function generateSQLFiles(pg: SupabaseDirectClient) { await fs.writeFile(`${outputDir}/views.sql`, viewsContent) - console.debug('Prettifying SQL files...') + debug('Prettifying SQL files...') execSync(`prettier --write ${outputDir}/*.sql --ignore-path ../supabase/.gitignore`) } diff --git a/backend/scripts/remove-tiptap-nodes.ts b/backend/scripts/remove-tiptap-nodes.ts index 6c170421..acc28056 100644 --- a/backend/scripts/remove-tiptap-nodes.ts +++ b/backend/scripts/remove-tiptap-nodes.ts @@ -1,6 +1,7 @@ import {runScript} from './run-script' import {from, renderSql, select, where} from 'shared/supabase/sql-builder' import {type JSONContent} from '@tiptap/core' +import {debug} from 'common/logger' const removeNodesOfType = (content: JSONContent, typeToRemove: string): JSONContent | null => { if (content.type === typeToRemove) { @@ -22,7 +23,7 @@ const removeNodesOfType = (content: JSONContent, typeToRemove: string): JSONCont runScript(async ({pg}) => { const nodeType = 'linkPreview' - console.debug('\nSearching comments for linkPreviews...') + debug('\nSearching comments for linkPreviews...') const commentQuery = renderSql( select('id, content'), from('profile_comments'), @@ -30,21 +31,21 @@ runScript(async ({pg}) => { ) const comments = await pg.manyOrNone(commentQuery) - console.debug(`Found ${comments.length} comments with linkPreviews`) + debug(`Found ${comments.length} comments with linkPreviews`) for (const comment of comments) { const newContent = removeNodesOfType(comment.content, nodeType) - console.debug('before', comment.content) - console.debug('after', newContent) + debug('before', comment.content) + debug('after', newContent) await pg.none('update profile_comments set content = $1 where id = $2', [ newContent, comment.id, ]) - console.debug('Updated comment:', comment.id) + debug('Updated comment:', comment.id) } - console.debug('\nSearching private messages for linkPreviews...') + debug('\nSearching private messages for linkPreviews...') const messageQuery = renderSql( select('id, content'), from('private_user_messages'), @@ -52,17 +53,17 @@ runScript(async ({pg}) => { ) const messages = await pg.manyOrNone(messageQuery) - console.debug(`Found ${messages.length} messages with linkPreviews`) + debug(`Found ${messages.length} messages with linkPreviews`) for (const msg of messages) { const newContent = removeNodesOfType(msg.content, nodeType) - console.debug('before', JSON.stringify(msg.content, null, 2)) - console.debug('after', JSON.stringify(newContent, null, 2)) + debug('before', JSON.stringify(msg.content, null, 2)) + debug('after', JSON.stringify(newContent, null, 2)) await pg.none('update private_user_messages set content = $1 where id = $2', [ newContent, msg.id, ]) - console.debug('Updated message:', msg.id) + debug('Updated message:', msg.id) } }) diff --git a/backend/scripts/run-script.ts b/backend/scripts/run-script.ts index 99a7ee48..dc561014 100644 --- a/backend/scripts/run-script.ts +++ b/backend/scripts/run-script.ts @@ -1,6 +1,7 @@ import {initAdmin} from 'shared/init-admin' import {createSupabaseDirectClient, type SupabaseDirectClient} from 'shared/supabase/init' import {refreshConfig} from 'common/envs/prod' +import {debug} from 'common/logger' export const runScript = async ( main: (services: {pg: SupabaseDirectClient}) => Promise | any, @@ -9,14 +10,14 @@ export const runScript = async ( initAdmin() await initEnvVariables() if (logEnv) { - console.debug('[runScript] Environment variables:') - for (const k of Object.keys(process.env)) console.debug(`${k}=${process.env[k]}`) + debug('[runScript] Environment variables:') + for (const k of Object.keys(process.env)) debug(`${k}=${process.env[k]}`) } - console.debug('[runScript] Creating Supabase client...') + debug('[runScript] Creating Supabase client...') const pg = createSupabaseDirectClient() - console.debug('[runScript] Running script...') + debug('[runScript] Running script...') await main({pg}) } diff --git a/backend/shared/src/firebase-utils.ts b/backend/shared/src/firebase-utils.ts index ceb0a4d4..cc5b682e 100644 --- a/backend/shared/src/firebase-utils.ts +++ b/backend/shared/src/firebase-utils.ts @@ -1,4 +1,5 @@ import {ENV_CONFIG, getStorageBucketId} from 'common/envs/constants' +import {debug} from 'common/logger' import {getStorage, Storage} from 'firebase-admin/storage' import {readFileSync} from 'fs' @@ -40,10 +41,10 @@ export async function deleteUserFiles(username: string) { const [files] = await bucket.getFiles({prefix: path}) if (files.length === 0) { - console.debug(`No files found in bucket for user ${username}`) + debug(`No files found in bucket for user ${username}`) return } await Promise.all(files.map((file) => file.delete())) - console.debug(`Deleted ${files.length} files for user ${username}`) + debug(`Deleted ${files.length} files for user ${username}`) } diff --git a/backend/shared/src/helpers/generate-and-update-avatar-urls.ts b/backend/shared/src/helpers/generate-and-update-avatar-urls.ts index be1ee12d..6f6fe6d2 100644 --- a/backend/shared/src/helpers/generate-and-update-avatar-urls.ts +++ b/backend/shared/src/helpers/generate-and-update-avatar-urls.ts @@ -1,4 +1,5 @@ import {DOMAIN} from 'common/envs/constants' +import {debug} from 'common/logger' import {Bucket} from 'shared/firebase-utils' export const generateAvatarUrl = async (userId: string, name: string, bucket: Bucket) => { @@ -21,7 +22,7 @@ export const generateAvatarUrl = async (userId: string, name: string, bucket: Bu const buffer = await res.arrayBuffer() return await upload(userId, Buffer.from(buffer), bucket) } catch (e) { - console.debug('error generating avatar', e) + debug('error generating avatar', e) return `https://${DOMAIN}/images/default-avatar.png` } } diff --git a/backend/shared/src/helpers/search.ts b/backend/shared/src/helpers/search.ts index fdc08855..4b7bff2a 100644 --- a/backend/shared/src/helpers/search.ts +++ b/backend/shared/src/helpers/search.ts @@ -1,9 +1,11 @@ +import {debug} from 'common/logger' + export const constructPrefixTsQuery = (term: string) => { const sanitized = term .replace(/'/g, "''") .replace(/[!&|():*<>]/g, '') .trim() - console.debug(`Term: "${sanitized}"`) + debug(`Term: "${sanitized}"`) if (sanitized === '') return '' const tokens = sanitized.split(/\s+/) return tokens.join(' & ') + ':*' diff --git a/backend/shared/src/init-admin.ts b/backend/shared/src/init-admin.ts index 23220efd..622c6c79 100644 --- a/backend/shared/src/init-admin.ts +++ b/backend/shared/src/init-admin.ts @@ -1,5 +1,6 @@ import {IS_FIREBASE_EMULATOR} from 'common/envs/constants' import {IS_LOCAL} from 'common/hosting/constants' +import {debug} from 'common/logger' import * as admin from 'firebase-admin' import {getServiceAccountCredentials} from 'shared/firebase-utils' @@ -17,10 +18,10 @@ export const initAdmin = () => { const serviceAccount = getServiceAccountCredentials() if (!serviceAccount.project_id) { - console.debug(`GOOGLE_APPLICATION_CREDENTIALS not set, skipping admin firebase init.`) + debug(`GOOGLE_APPLICATION_CREDENTIALS not set, skipping admin firebase init.`) return } - console.debug(`Initializing connection to ${serviceAccount.project_id} Firebase...`) + debug(`Initializing connection to ${serviceAccount.project_id} Firebase...`) return admin.initializeApp({ projectId: serviceAccount.project_id, credential: admin.credential.cert(serviceAccount), @@ -31,6 +32,6 @@ export const initAdmin = () => { } } - console.debug(`Initializing connection to default Firebase...`) + debug(`Initializing connection to default Firebase...`) return admin.initializeApp() } diff --git a/common/src/envs/constants.ts b/common/src/envs/constants.ts index b47226d2..cf4b5f5d 100644 --- a/common/src/envs/constants.ts +++ b/common/src/envs/constants.ts @@ -12,7 +12,11 @@ import {PROD_CONFIG} from './prod' export const MAX_DESCRIPTION_LENGTH = 100000 export const MAX_ANSWER_LENGTH = 240 -export const ENV_CONFIG = isProd() ? PROD_CONFIG : DEV_CONFIG +export const ENV = isProd() ? 'prod' : 'dev' +export const IS_PROD = ENV === 'prod' +export const IS_DEV = ENV === 'dev' + +export const ENV_CONFIG = IS_PROD ? PROD_CONFIG : DEV_CONFIG export function isAdminId(id: string) { return ENV_CONFIG.adminIds.includes(id) @@ -22,10 +26,6 @@ export function isModId(id: string) { return MOD_USERNAMES.includes(id) } -export const ENV = isProd() ? 'prod' : 'dev' -// export const IS_PROD = ENV === 'prod' -export const IS_DEV = ENV === 'dev' - console.debug(`Running in ${HOSTING_ENV} (${ENV})`) // class MissingKeyError implements Error { diff --git a/common/src/geodb.ts b/common/src/geodb.ts index f81943ad..cd7d588b 100644 --- a/common/src/geodb.ts +++ b/common/src/geodb.ts @@ -1,3 +1,4 @@ +import {debug} from 'common/logger' import {ProfileRow} from 'common/profiles/profile' export const geodbHost = 'wft-geo-db.p.rapidapi.com' @@ -24,10 +25,10 @@ export const geodbFetch = async (endpoint: string) => { } const data = await res.json() - console.debug('geodbFetch', endpoint, data) + debug('geodbFetch', endpoint, data) return {status: 'success', data} } catch (error) { - console.debug('geodbFetch', endpoint, error) + debug('geodbFetch', endpoint, error) return {status: 'failure', data: error} } } diff --git a/web/lib/logger.ts b/common/src/logger.ts similarity index 83% rename from web/lib/logger.ts rename to common/src/logger.ts index 3c01a746..5a164b84 100644 --- a/web/lib/logger.ts +++ b/common/src/logger.ts @@ -1,3 +1,5 @@ +import {IS_PROD} from 'common/envs/constants' + type LogLevel = 'debug' | 'info' | 'warn' | 'error' interface LogContext { @@ -13,11 +15,6 @@ const LOG_LEVELS: Record = { error: 3, } -const currentLevel = (): LogLevel => { - if (process.env.NODE_ENV === 'production') return 'info' - return 'debug' -} - function shouldLog(level: LogLevel): boolean { return LOG_LEVELS[level] >= LOG_LEVELS[currentLevel()] } @@ -59,12 +56,27 @@ export const logger = { export function logApiError(endpoint: string, error: Error | unknown, extra?: LogContext): void { const errorMessage = error instanceof Error ? error.message : String(error) - logger.error(`API Error in ${endpoint}`, error instanceof Error ? error : new Error(errorMessage), { - endpoint, - ...extra, - }) + logger.error( + `API Error in ${endpoint}`, + error instanceof Error ? error : new Error(errorMessage), + { + endpoint, + ...extra, + }, + ) } export function logPageView(path: string): void { logger.info('Page view', {path}) } + +const currentLevel = (): LogLevel => { + if (IS_PROD) return 'info' + return 'debug' +} + +export const debug = (...args: unknown[]) => { + if (currentLevel() === 'debug') { + console.debug(...args) + } +} diff --git a/common/src/logging.ts b/common/src/logging.ts deleted file mode 100644 index f20f7c62..00000000 --- a/common/src/logging.ts +++ /dev/null @@ -1,62 +0,0 @@ -import {IS_LOCAL} from 'common/hosting/constants' - -class Logger { - private readonly isLocal: boolean - - constructor(isLocal = false) { - this.isLocal = isLocal - } - - trace(...args: any[]) { - // Does not seem to really work. Was trying to show the real file where the log was called from. - if (!this.isLocal) return - - const caller = this.getCallerFrame(3) // skip Logger frames - if (caller) { - console.log('Trace:', ...args, '\nCalled from:', caller) - } else { - console.trace(...args) - } - } - - log(...args: any[]) { - if (this.isLocal) console.log(...args) - } - - info(...args: any[]) { - if (this.isLocal) console.info(...args) - } - - warn(...args: any[]) { - if (this.isLocal) console.warn(...args) - } - - error(...args: any[]) { - if (this.isLocal) console.error(...args) - } - - debug(...args: any[]) { - if (this.isLocal) console.debug(...args) - } - - table(...args: any[]) { - if (this.isLocal) console.table(...args) - } - - group(...args: any[]) { - if (this.isLocal) console.group(...args) - } - - private getCallerFrame(skip = 2): string | undefined { - // Create an Error to get stack trace - const err = new Error() - if (!err.stack) return undefined - - const lines = err.stack.split('\n') - - // skip frames (0: Error, 1: Logger method, 2+: caller) - return lines[skip]?.trim() - } -} - -export const logger = new Logger(IS_LOCAL) diff --git a/common/src/profiles/constants.ts b/common/src/profiles/constants.ts index a7c122e7..37b19119 100644 --- a/common/src/profiles/constants.ts +++ b/common/src/profiles/constants.ts @@ -1,6 +1,6 @@ -import {isProd} from 'common/envs/is-prod' +import {IS_PROD} from 'common/envs/constants' -export const compassUserId = isProd() +export const compassUserId = IS_PROD ? 'tRZZ6ihugZQLXPf6aPRneGpWLmz1' : 'RlXR2xa4EFfAzdCbSe45wkcdarh1' diff --git a/common/src/secrets.ts b/common/src/secrets.ts index 4785b7ff..b58322ac 100644 --- a/common/src/secrets.ts +++ b/common/src/secrets.ts @@ -1,6 +1,7 @@ import {SecretManagerServiceClient} from '@google-cloud/secret-manager' import {refreshConfig} from 'common/envs/prod' import {IS_LOCAL} from 'common/hosting/constants' +import {debug} from 'common/logger' import {zip} from 'lodash' // List of secrets that are available to backend (api, functions, scripts, etc.) @@ -54,7 +55,7 @@ export const getSecrets = async (credentials?: any, ...ids: SecretId[]) => { const secretIds = ids.length > 0 ? ids : secrets - console.debug('secretIds', secretIds) + debug('secretIds', secretIds) const fullSecretNames = secretIds.map( (secret: string) => `${client.projectPath(projectId)}/secrets/${secret}/versions/latest`, diff --git a/common/src/util/matrix.ts b/common/src/util/matrix.ts index 07e6bcc4..a9b0364e 100644 --- a/common/src/util/matrix.ts +++ b/common/src/util/matrix.ts @@ -1,3 +1,4 @@ +import {debug} from 'common/logger' import {max, sumBy} from 'lodash' // each row has [column, value] pairs @@ -32,7 +33,7 @@ export function factorizeMatrix( const mFeatures = fillMatrix(m, FEATURES, initCell) const nFeatures = fillMatrix(n, FEATURES, initCell) - console.debug('rows', m, 'columns', n, 'numPoints', points) + debug('rows', m, 'columns', n, 'numPoints', points) const updateFeature = (a: number, b: number, error: number) => a + LEARNING_RATE * (2 * error * b - REGULARIZATION_RATE * a) @@ -75,7 +76,7 @@ export function factorizeMatrix( } } } - console.debug(iter, 'error', totalError / points) + debug(iter, 'error', totalError / points) // Complete factorization process if total error falls below a certain threshold if (totalError / points < THRESHOLD) break diff --git a/web/components/SEO.tsx b/web/components/SEO.tsx index 605b82bd..60c2f82e 100644 --- a/web/components/SEO.tsx +++ b/web/components/SEO.tsx @@ -1,4 +1,4 @@ -import {isProd} from 'common/envs/is-prod' +import {IS_PROD} from 'common/envs/constants' import {removeUndefinedProps} from 'common/util/object' import {buildOgUrl} from 'common/util/og' import Head from 'next/head' @@ -16,7 +16,7 @@ export function SEO

>(props: { image ?? (ogProps && buildOgUrl(removeUndefinedProps(ogProps.props) as any, ogProps.endpoint)) const absUrl = 'https://compassmeet.com' + url - const endTitle = isProd() ? 'Compass' : 'Compass dev' + const endTitle = IS_PROD ? 'Compass' : 'Compass dev' return ( diff --git a/web/components/answers/add-compatibility-question-button.tsx b/web/components/answers/add-compatibility-question-button.tsx index c90ee37e..4c28725a 100644 --- a/web/components/answers/add-compatibility-question-button.tsx +++ b/web/components/answers/add-compatibility-question-button.tsx @@ -1,5 +1,6 @@ import {PlusIcon, XIcon} from '@heroicons/react/outline' import {MAX_ANSWER_LENGTH} from 'common/envs/constants' +import {debug} from 'common/logger' import {MAX_COMPATIBILITY_QUESTION_LENGTH} from 'common/profiles/constants' import {Row as rowFor} from 'common/supabase/utils' import {User} from 'common/user' @@ -53,7 +54,7 @@ function AddCompatibilityQuestionModal(props: { const [dbQuestion, setDbQuestion] = useState | null>(null) const afterAddQuestion = (newQuestion: rowFor<'compatibility_prompts'>) => { setDbQuestion(newQuestion) - console.debug('setDbQuestion', newQuestion) + debug('setDbQuestion', newQuestion) } return ( @@ -132,7 +133,7 @@ function CreateCompatibilityModalContent(props: { options: generateJson(), } const newQuestion = await api('create-compatibility-question', data) - console.debug('create-compatibility-question', newQuestion, data) + debug('create-compatibility-question', newQuestion, data) const q = newQuestion?.question if (q) { afterAddQuestion(q as rowFor<'compatibility_prompts'>) diff --git a/web/components/filters/use-filters.ts b/web/components/filters/use-filters.ts index 19e4a6a8..a12cbffc 100644 --- a/web/components/filters/use-filters.ts +++ b/web/components/filters/use-filters.ts @@ -1,7 +1,7 @@ import {LOCALE_TO_LANGUAGE} from 'common/choices' import {MAX_INT, MIN_INT} from 'common/constants' import {FilterFields, initialFilters, OriginLocation} from 'common/filters' -import {logger} from 'common/logging' +import {debug} from 'common/logger' import {kmToMiles} from 'common/measurement-utils' import {Profile} from 'common/profiles/profile' import { @@ -141,7 +141,7 @@ export const useFilters = (you: Profile | undefined, fromSignup?: boolean) => { has_kids: wantsKidsToHasKidsFilter((you?.wants_kids_strength ?? 2) as wantsKidsDatabase), is_smoker: you?.is_smoker, } - logger.debug(you, yourFilters) + debug(you, yourFilters) const isYourFilters = !!you && diff --git a/web/components/optional-profile-form.tsx b/web/components/optional-profile-form.tsx index d1aef161..1d3d9c64 100644 --- a/web/components/optional-profile-form.tsx +++ b/web/components/optional-profile-form.tsx @@ -14,6 +14,7 @@ import { RELIGION_CHOICES, ROMANTIC_CHOICES, } from 'common/choices' +import {debug} from 'common/logger' import {MultipleChoiceOptions} from 'common/profiles/multiple-choice' import {getProfileRow, Profile, ProfileWithoutUser} from 'common/profiles/profile' import {PLATFORM_LABELS, type Site, SITE_ORDER} from 'common/socials' @@ -148,7 +149,7 @@ export const OptionalProfileUserForm = (props: { work, ...otherProfileProps } = profile - console.debug('otherProfileProps', removeUndefinedProps(otherProfileProps)) + debug('otherProfileProps', removeUndefinedProps(otherProfileProps)) const promises: Promise[] = [ tryCatch(updateProfile(removeUndefinedProps(otherProfileProps) as any)), ] @@ -1050,7 +1051,7 @@ export const OptionalProfileUserForm = (props: { { - console.debug('bio changed', e, profile.bio) + debug('bio changed', e, profile.bio) setProfile('bio', e.getJSON()) setProfile('bio_length', e.getText().length) }} diff --git a/web/components/profile/profile-header.tsx b/web/components/profile/profile-header.tsx index 934407cf..549c69b5 100644 --- a/web/components/profile/profile-header.tsx +++ b/web/components/profile/profile-header.tsx @@ -1,5 +1,6 @@ import {DotsHorizontalIcon, EyeIcon, LockClosedIcon, PencilIcon} from '@heroicons/react/outline' import clsx from 'clsx' +import {debug} from 'common/logger' import {Profile} from 'common/profiles/profile' import {User, UserActivity} from 'common/user' import {capitalize} from 'lodash' @@ -55,7 +56,7 @@ export default function ProfileHeader(props: { const disabled = profile.disabled const t = useT() - console.debug('ProfileProfileHeader', { + debug('ProfileProfileHeader', { user, profile, userActivity, diff --git a/web/components/profile/profile-info.tsx b/web/components/profile/profile-info.tsx index e91bc80c..68035bba 100644 --- a/web/components/profile/profile-info.tsx +++ b/web/components/profile/profile-info.tsx @@ -1,4 +1,5 @@ import {JSONContent} from '@tiptap/core' +import {debug} from 'common/logger' import {Profile} from 'common/profiles/profile' import {UserActivity} from 'common/user' import {ProfileAnswers} from 'web/components/answers/profile-answers' @@ -29,7 +30,7 @@ export function ProfileInfo(props: { fromSignup?: boolean }) { const {profile, user, refreshProfile, fromProfilePage, fromSignup} = props - console.debug('Rendering Profile for', user.username, user.name, props) + debug('Rendering Profile for', user.username, user.name, props) const currentUser = useUser() const t = useT() diff --git a/web/components/profiles/profiles-home.tsx b/web/components/profiles/profiles-home.tsx index 1ecc8856..62f67f70 100644 --- a/web/components/profiles/profiles-home.tsx +++ b/web/components/profiles/profiles-home.tsx @@ -1,3 +1,4 @@ +import {debug} from 'common/logger' import {Profile} from 'common/profiles/profile' import {removeNullOrUndefinedProps} from 'common/util/object' import {DAY_MS} from 'common/util/time' @@ -96,7 +97,7 @@ export function ProfilesHome() { locale, ...filters, }) - console.debug('Refreshing profiles, filters:', args) + debug('Refreshing profiles, filters:', args) api('get-profiles', args as any) .then(({profiles, count}) => { if (current === id.current) { diff --git a/web/components/site-logo.tsx b/web/components/site-logo.tsx index f96c6eb9..a8ae184c 100644 --- a/web/components/site-logo.tsx +++ b/web/components/site-logo.tsx @@ -1,5 +1,5 @@ import clsx from 'clsx' -import {isProd} from 'common/envs/is-prod' +import {IS_PROD} from 'common/envs/constants' import Link from 'next/link' import FavIcon from 'web/components/FavIcon' import {Row} from 'web/components/layout/row' @@ -10,7 +10,7 @@ export default function SiteLogo(props: {noLink?: boolean; className?: string}) <>

- {isProd() ? 'Compass' : 'Compass dev'} + {IS_PROD ? 'Compass' : 'Compass dev'}
) diff --git a/web/components/votes/vote-info.tsx b/web/components/votes/vote-info.tsx index 613a3517..de876512 100644 --- a/web/components/votes/vote-info.tsx +++ b/web/components/votes/vote-info.tsx @@ -1,6 +1,7 @@ import {JSONContent} from '@tiptap/core' import {formLink} from 'common/constants' import {MAX_DESCRIPTION_LENGTH} from 'common/envs/constants' +import {debug} from 'common/logger' import {ORDER_BY, ORDER_BY_CHOICES, OrderBy} from 'common/votes/constants' import Link from 'next/link' import {useEffect, useState} from 'react' @@ -113,7 +114,7 @@ export function VoteComponent() { setTitle('') editor.commands.clearContent() toast.success(t('vote.toast.created', 'Vote created')) - console.debug('Vote created', newVote) + debug('Vote created', newVote) refreshVotes() }} > diff --git a/web/hooks/use-nearby-locations.ts b/web/hooks/use-nearby-locations.ts index aa1b0322..dfbef815 100644 --- a/web/hooks/use-nearby-locations.ts +++ b/web/hooks/use-nearby-locations.ts @@ -1,3 +1,4 @@ +import {debug} from 'common/logger' import {useEffect, useRef} from 'react' import {usePersistentLocalState} from 'web/hooks/use-persistent-local-state' import {api} from 'web/lib/api' @@ -17,7 +18,7 @@ export function useNearbyCities(referenceCityId: string | null | undefined, radi cityId: referenceCityId, radius, }).then((result) => { - console.debug('search-near-city', result) + debug('search-near-city', result) if (thisSearchCount == searchCount.current) { if (result.status === 'failure') { setNearbyCities(null) diff --git a/web/hooks/use-profile.ts b/web/hooks/use-profile.ts index 31a566de..a93c418e 100644 --- a/web/hooks/use-profile.ts +++ b/web/hooks/use-profile.ts @@ -1,3 +1,4 @@ +import {debug} from 'common/logger' import {getProfileRow, Profile, ProfileWithoutUser} from 'common/profiles/profile' import {Row} from 'common/supabase/utils' import {User} from 'common/user' @@ -47,11 +48,11 @@ export const useProfileByUser = (user: User | undefined) => { else setProfile({...profile, user}) }) .catch((error) => { - console.debug('Warning: profile not found', user?.username, error) + debug('Warning: profile not found', user?.username, error) setProfile(null) return }) - console.debug('End Refreshing profile for', user?.username, profile) + debug('End Refreshing profile for', user?.username, profile) } } diff --git a/web/hooks/use-user.ts b/web/hooks/use-user.ts index de02a48f..7fc7a2c0 100644 --- a/web/hooks/use-user.ts +++ b/web/hooks/use-user.ts @@ -1,4 +1,5 @@ 'use client' +import {debug} from 'common/logger' import {PrivateUser, User} from 'common/user' import {useContext, useEffect, useState} from 'react' import {AuthContext} from 'web/components/auth-context' @@ -30,7 +31,7 @@ export const useWebsocketUser = (userId: string | undefined) => { useApiSubscription({ topics: [`user/${userId ?? '_'}`], onBroadcast: ({data}) => { - console.debug('User broadcast', {data}) + debug('User broadcast', {data}) setUser((user) => { if (!user || !data.user) { return user diff --git a/web/lib/api.ts b/web/lib/api.ts index e02cc2e6..168aedc8 100644 --- a/web/lib/api.ts +++ b/web/lib/api.ts @@ -1,4 +1,5 @@ import {API, APIParams, APIPath} from 'common/api/schema' +import {debug} from 'common/logger' import {typedAPICall} from 'common/util/api' import {sleep} from 'common/util/time' @@ -16,7 +17,7 @@ export async function api

(path: P, params: APIParams

= {}) break } } - console.debug('User loaded after', i, 'iterations') + debug('User loaded after', i, 'iterations') } return typedAPICall(path, params, auth.currentUser) @@ -32,7 +33,7 @@ export const report = curriedAPI('report') export const updateBackendLocale = (newLocale: string) => { if (!auth.currentUser) return - console.debug('Updating backend locale to', newLocale) + debug('Updating backend locale to', newLocale) api('update-user-locale', {locale: newLocale}).catch((error) => { console.error('Failed to update user locale:', error) }) diff --git a/web/lib/firebase/google-onetap-login.tsx b/web/lib/firebase/google-onetap-login.tsx index e1faf89f..869f333e 100644 --- a/web/lib/firebase/google-onetap-login.tsx +++ b/web/lib/firebase/google-onetap-login.tsx @@ -1,4 +1,5 @@ 'use client' +import {debug} from 'common/logger' import {GoogleAuthProvider, signInWithCredential} from 'firebase/auth' import Script from 'next/script' import {useEffect} from 'react' @@ -11,7 +12,7 @@ async function handleResponse(response: any) { const credential = GoogleAuthProvider.credential(idToken) try { const result = await signInWithCredential(auth, credential) - console.debug(result.user) + debug(result.user) } catch (error) { console.error('could not log in via onetap', error) } diff --git a/web/pages/[username]/index.tsx b/web/pages/[username]/index.tsx index 42e330b2..51cc3798 100644 --- a/web/pages/[username]/index.tsx +++ b/web/pages/[username]/index.tsx @@ -1,4 +1,5 @@ import {JSONContent} from '@tiptap/core' +import {debug} from 'common/logger' import {getProfileOgImageUrl} from 'common/profiles/og-image' import {getProfileRow, ProfileRow} from 'common/profiles/profile' import {getUserForStaticProps} from 'common/supabase/users' @@ -42,7 +43,7 @@ async function getProfile(userId: string) { break } } - console.debug(`Profile loaded after ${i} tries`) + debug(`Profile loaded after ${i} tries`) return profile } @@ -81,10 +82,10 @@ export const getStaticProps = async ( const user = await getUser(username) - console.debug('getStaticProps', {user}) + debug('getStaticProps', {user}) if (!user) { - console.debug('No user') + debug('No user') return { props: { notFoundCustomText: @@ -95,7 +96,7 @@ export const getStaticProps = async ( } if (user.username !== username) { - console.debug('Found a case-insensitive match') + debug('Found a case-insensitive match') // Found a case-insensitive match, redirect to correct casing return { redirect: { @@ -106,7 +107,7 @@ export const getStaticProps = async ( } if (user.userDeleted) { - console.debug('User deleted') + debug('User deleted') return { props: { username, @@ -118,7 +119,7 @@ export const getStaticProps = async ( const profile = await getProfile(user.id) if (!profile) { - console.debug('No profile', `${user.username} hasn't created a profile yet.`) + debug('No profile', `${user.username} hasn't created a profile yet.`) return { props: { notFoundCustomText: `${user.username} hasn't created a profile yet.`, @@ -126,7 +127,7 @@ export const getStaticProps = async ( revalidate: 1, } } - // console.debug('profile', profile) + // debug('profile', profile) return { props: { user, @@ -260,7 +261,7 @@ export default function UserPage(props: UserPageProps) { } function UserPageInner(props: ActiveUserPageProps) { - // console.debug('Starting UserPageInner in /[username]') + // debug('Starting UserPageInner in /[username]') const {user, username} = props const router = useRouter() const {query} = router @@ -276,7 +277,7 @@ function UserPageInner(props: ActiveUserPageProps) { const {profile: clientProfile, refreshProfile} = useProfileByUser(user) // Show the previous profile while loading another one const profile = clientProfile ?? staticProfile - // console.debug('profile:', user?.username, profile, clientProfile, staticProfile) + // debug('profile:', user?.username, profile, clientProfile, staticProfile) if (!isCurrentUser && profile?.disabled) { return ( diff --git a/web/pages/index.tsx b/web/pages/index.tsx index 8eddef2b..b4cd21b4 100644 --- a/web/pages/index.tsx +++ b/web/pages/index.tsx @@ -1,3 +1,4 @@ +import {debug} from 'common/logger' import {LoggedOutHome} from 'web/components/home/home' import {Col} from 'web/components/layout/col' import {PageBase} from 'web/components/page-base' @@ -17,7 +18,7 @@ export default function ProfilesPage() { return } - console.debug('user:', user) + debug('user:', user) return ( diff --git a/web/pages/register.tsx b/web/pages/register.tsx index 7d6fe416..3a2e0ff1 100644 --- a/web/pages/register.tsx +++ b/web/pages/register.tsx @@ -1,5 +1,6 @@ 'use client' +import {debug} from 'common/logger' import {getProfileRow} from 'common/profiles/profile' import {createUserWithEmailAndPassword} from 'firebase/auth' import Link from 'next/link' @@ -61,7 +62,7 @@ function RegisterComponent() { const handleEmailPasswordSignUp = async (email: string, password: string) => { try { const creds = await createUserWithEmailAndPassword(auth, email, password) - console.debug('User signed up:', creds.user) + debug('User signed up:', creds.user) } catch (error: any) { console.error('Error signing up:', error) toast.error(t('register.toast.signup_failed', 'Failed to sign up: ') + (error?.message ?? '')) diff --git a/web/pages/signin.tsx b/web/pages/signin.tsx index 8e28b14d..91909c2d 100644 --- a/web/pages/signin.tsx +++ b/web/pages/signin.tsx @@ -1,6 +1,6 @@ 'use client' -import {logger} from 'common/logging' +import {debug} from 'common/logger' import {getProfileRow} from 'common/profiles/profile' import {signInWithEmailAndPassword} from 'firebase/auth' import Link from 'next/link' @@ -45,7 +45,7 @@ function RegisterComponent() { useEffect(() => { const checkAndRedirect = async () => { if (user) { - console.debug('User signed in:', user) + debug('User signed in:', user) try { const profile = await getProfileRow(user.id, db) if (profile) { @@ -68,7 +68,7 @@ function RegisterComponent() { setError(null) try { const creds = await firebaseLogin() - logger.debug('creds', creds) + debug('creds', creds) if (creds) { setIsLoading(true) setIsLoadingGoogle(true) @@ -85,7 +85,7 @@ function RegisterComponent() { const handleEmailPasswordSignIn = async (email: string, password: string) => { try { const creds = await signInWithEmailAndPassword(auth, email, password) - logger.debug(creds) + debug(creds) } catch (error) { console.error('Error signing in:', error) const message = t( diff --git a/web/pages/signup.tsx b/web/pages/signup.tsx index 854dc29a..a211736e 100644 --- a/web/pages/signup.tsx +++ b/web/pages/signup.tsx @@ -1,4 +1,5 @@ import {LOCALE_TO_LANGUAGE} from 'common/choices' +import {debug} from 'common/logger' import {ProfileWithoutUser} from 'common/profiles/profile' import {removeNullOrUndefinedProps} from 'common/util/object' import {useRouter} from 'next/router' @@ -162,7 +163,7 @@ export default function SignupPage() { : undefined setIsSubmitting(true) - console.debug('profileForm', profileForm) + debug('profileForm', profileForm) const profile = await api( 'create-profile', removeNullOrUndefinedProps({ diff --git a/web/tests/unit/logger.test.ts b/web/tests/unit/logger.test.ts index ac145b72..4f2a6689 100644 --- a/web/tests/unit/logger.test.ts +++ b/web/tests/unit/logger.test.ts @@ -1,4 +1,4 @@ -import {logApiError, logger} from 'web/lib/logger' +import {logApiError, logger} from 'common/lib/logger' describe('logger', () => { const originalEnv = process.env.NODE_ENV