Skip to content

Commit

Permalink
refactor: use axiom log instead of console
Browse files Browse the repository at this point in the history
  • Loading branch information
devrsi0n committed Aug 26, 2022
1 parent 3912600 commit 2fcf0e8
Show file tree
Hide file tree
Showing 26 changed files with 57 additions and 39 deletions.
2 changes: 1 addition & 1 deletion apps/main/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
"lodash": "4.17.21",
"next": "12.2.5",
"next-auth": "4.10.3",
"next-axiom": "^0.13.0",
"next-axiom": "0.13.0",
"next-compose-plugins": "2.2.1",
"next-connect": "0.12.2",
"next-mdx-remote": "3.0.8",
Expand Down
3 changes: 2 additions & 1 deletion apps/main/src/__tests__/pages/auth/welcome.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@ import { pageRender } from '$/__tests__/fixtures/page-render';
import { setMockedUser } from '$/__tests__/fixtures/page-render';
import { mockNextRouter } from '$/__tests__/mocks/next-router';
import * as UserModule from '$/graphql/generated/user';
import { logger } from '$/lib/logger';
import Welcome from '$/pages/auth/welcome';

const mockUpdateUser = jest.fn().mockImplementation(() => {
console.log('called mockUpdateUser');
logger.debug('called mockUpdateUser');
});
jest.mock('$/graphql/generated/user', () => ({
// Make exported object configurable
Expand Down
2 changes: 1 addition & 1 deletion apps/main/src/blocks/analytics/stats/modals/sources.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ class SourcesModal extends React.Component {
if (filter === 'utm_sources') query.set('utm_source', source.name);
if (filter === 'utm_campaigns') query.set('utm_campaign', source.name);

// console.log(source);
// logger.debug(source);

return (
<tr className="text-sm dark:text-gray-200" key={source.name}>
Expand Down
3 changes: 2 additions & 1 deletion apps/main/src/blocks/comment-card/comment-card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { useToast } from '$/components/toast';
import { useCommentContext } from '$/contexts/comment-context';
import { useCurrentUser } from '$/contexts/current-user-context';
import { COMMENT_TREE_MAX_DEPTH } from '$/lib/constants';
import { logger } from '$/lib/logger';
import { isENVDev } from '$/server/utilities/env';
import { CommentLeafType } from '$/types/widget';
import { dayjs } from '$/utilities/date';
Expand Down Expand Up @@ -71,7 +72,7 @@ export function CommentCard({
type: 'error',
title: 'Replied failed, try again later',
});
console.error('Replied failed', error);
logger.error('Replied failed', error);
}
};
const handleDimissRTE = () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ Default.play = async ({ canvasElement }) => {
function getUrqlParameter(data: CurrentNotificationMessagesSubscription) {
return (op: Operation) => {
const query = getOperationName(op.query);
// console.log({ op, subscription: query });
// logger.debug({ op, subscription: query });
if (query === 'currentNotificationMessages') {
return {
data,
Expand Down
3 changes: 2 additions & 1 deletion apps/main/src/blocks/project-card/page-view-stats.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { IconArrowUp } from '$/components/icons';
import { Link } from '$/components/link';
import { Text } from '$/components/text';
import { ANALYTICS_DOMAIN } from '$/lib/constants';
import { logger } from '$/lib/logger';

import { getStats } from '../analytics/analytics-api';

Expand All @@ -31,7 +32,7 @@ export function PageViewStats({ domain }: PageViewStatsProps): JSX.Element {
}
})
.catch(() => {
console.log('No stats data');
logger.debug('No stats data');
});
}, [domain]);
return (
Expand Down
3 changes: 2 additions & 1 deletion apps/main/src/blocks/project-card/project-card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { Text } from '$/components/text';
import { useToast } from '$/components/toast';
import { useDeleteProjectByPkMutation } from '$/graphql/generated/project';
import { UserDashboardProjectsQuery } from '$/graphql/generated/user';
import { logger } from '$/lib/logger';
import { listHoverable } from '$/styles/common';
import { dayjs } from '$/utilities/date';

Expand Down Expand Up @@ -52,7 +53,7 @@ export function ProjectCard({
setDeletingProject('');
onDeletedProject();
} catch (error) {
console.error(error);
logger.error('Delete project failed', error);
showToast({
type: 'error',
title:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { JsonArray } from 'type-fest';
import { RTEValue } from '$/blocks/rich-text-editor';
import { useToast } from '$/components/toast';
import { useInsertOneCommentMutation } from '$/graphql/generated/comment';
import { logger } from '$/lib/logger';

import { useCurrentUser } from '../current-user-context';

Expand All @@ -19,7 +20,7 @@ export function useCreateAComment({ pageId }: useCreateACommentOptions) {

const createAComment = async (reply: RTEValue, commentId?: string) => {
if (!isSignIn) {
console.error('Navigate to sign-in page');
logger.error('Navigate to sign-in page');
throw undefined;
}
const { data } = await insertOneComment({
Expand All @@ -32,7 +33,7 @@ export function useCreateAComment({ pageId }: useCreateACommentOptions) {
type: 'error',
title: `Server didn't respond, please try again later.`,
});
console.error(`Can't insert a comment, parentId ${commentId}`);
logger.error(`Can't insert a comment, parentId ${commentId}`);
}
};
return createAComment;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
useInsertOneLikeMutation,
} from '$/graphql/generated/like';
import { useSignInWindow } from '$/hooks/use-sign-in-window';
import { logger } from '$/lib/logger';

export type UseToggleALikeAction = ReturnType<typeof useToggleALikeAction>;

Expand Down Expand Up @@ -32,7 +33,7 @@ export function useToggleALikeAction() {
id: likeId,
});
if (!data?.deleteLikeByPk?.id) {
console.error(`Can't delete the like, id ${likeId}`);
logger.error(`Can't delete the like, id ${likeId}`);
}
} else {
try {
Expand All @@ -44,7 +45,7 @@ export function useToggleALikeAction() {
type: 'error',
title: `Server didn't respond, please try again later.`,
});
console.error(`Can't create a like action`);
logger.error(`Can't create a like action`);
}
} catch (error) {
showToast({
Expand All @@ -54,7 +55,7 @@ export function useToggleALikeAction() {
// There is a `Unique constraint failed on the fields: (`userId`,`commentId`)` error
// when a user click the like button again during this API processing
// TODO: Refresh UI immediately, call APIs in the background
console.error(error);
logger.error('Insert a like', error);
}
}
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as React from 'react';

import { logger } from '$/lib/logger';
import { asyncNoop, noop } from '$/utilities/isomorphic/function';

import { useCurrentUser } from '../current-user-context';
Expand Down Expand Up @@ -37,14 +38,14 @@ export function NotificationProvider({ children }: INotificationProviderProps) {
return;
}
if (Notification.permission === 'denied') {
return console.log('Notification permission denied');
return logger.debug('Notification permission denied');
} else if (Notification.permission === 'default') {
const permission = await askNotificationPermission();
if (permission === 'denied') {
setDidDeny(true);
}
if (permission === 'denied' || permission === 'default') {
return console.log(`User didn't grant notification permission`);
return logger.debug(`User didn't grant notification permission`);
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as React from 'react';

import { useToast } from '$/components/toast';
import { logger } from '$/lib/logger';

import { checkServiceWorkerCompatibility } from './utilities';

Expand All @@ -18,7 +19,7 @@ export function useReloadWhenSwChange() {
navigator.serviceWorker.addEventListener('controllerchange', () => {
if (refreshing) return; // prevent infinite refresh loop when we use "Update on Reload" in DevTool
refreshing = true;
console.log('Controller loaded');
logger.debug('Controller loaded');
window.location.reload();
});
}, []);
Expand Down
7 changes: 4 additions & 3 deletions apps/main/src/contexts/notification-context/utilities.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { logger } from '$/lib/logger';
import { urlBase64ToUint8Array } from '$/utilities/string';

const NOTIFICATION_DID_REGISTER_KEY =
Expand Down Expand Up @@ -42,7 +43,7 @@ export function registerNotificationSubscription(): Promise<Response | void> {
});
})
.catch((error) => {
console.error('Service worker registration failed', error);
logger.error('Service worker registration failed', error);
throw error;
});
}
Expand All @@ -51,7 +52,7 @@ const SERVICE_WORKER_ERROR = 'Service worker not supported';
export function checkServiceWorkerCompatibility(): boolean {
const supported = 'serviceWorker' in navigator;
if (!supported) {
console.error(SERVICE_WORKER_ERROR);
logger.error(SERVICE_WORKER_ERROR);
}
return supported;
}
Expand All @@ -60,7 +61,7 @@ const NOTIFICATION_ERROR = 'This browser does not support notifications.';
export function checkNotificationCompatibility(): boolean {
const supported = 'Notification' in window;
if (!supported) {
console.error(NOTIFICATION_ERROR);
logger.error(NOTIFICATION_ERROR);
}
return supported;
}
Expand Down
9 changes: 5 additions & 4 deletions apps/main/src/hooks/use-local-storage.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Dispatch, SetStateAction, useEffect, useState } from 'react';

import { logger } from '$/lib/logger';
import { isSSRMode } from '$/utilities/env';

import { useEventListener } from './use-event-listener';
Expand All @@ -21,7 +22,7 @@ export function useLocalStorage<T>(
const item = window.localStorage.getItem(key);
return item ? (parseJSON(item) as T) : initialValue;
} catch (error) {
console.warn(`Error reading localStorage key “${key}”:`, error);
logger.warn(`Error reading localStorage key “${key}”:`, error);
return initialValue;
}
};
Expand All @@ -30,7 +31,7 @@ export function useLocalStorage<T>(
const customEventKey = `local-storage.${key}` as const;
const setValue: SetValue<T | undefined> = (value) => {
if (typeof window == 'undefined') {
console.warn(
logger.warn(
`Tried setting localStorage key “${key}” even though environment is not a client`,
);
}
Expand All @@ -47,7 +48,7 @@ export function useLocalStorage<T>(

window.dispatchEvent(new Event(customEventKey));
} catch (error) {
console.warn(`Error setting localStorage key “${key}”:`, error);
logger.warn(`Error setting localStorage key “${key}”:`, error);
}
};

Expand Down Expand Up @@ -79,7 +80,7 @@ function parseJSON<T>(value: string | null): T | undefined {
try {
return value === 'undefined' ? undefined : JSON.parse(value ?? '');
} catch {
console.log('parsing error on', { value });
logger.warn('parsing error on', { value });
return undefined;
}
}
3 changes: 3 additions & 0 deletions apps/main/src/lib/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { log } from 'next-axiom/dist/logger';

export const logger = log.with({ scope: 'frontend' });
2 changes: 1 addition & 1 deletion apps/main/src/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ function App({

export default App;

export { reportWebVitals } from 'next-axiom';
export { reportWebVitals } from 'next-axiom/dist/webVitals';

export const loadFeatures = () =>
import(
Expand Down
4 changes: 2 additions & 2 deletions apps/main/src/pages/api/auth/[...nextauth].ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import NextAuth from 'next-auth';
import { withAxiom } from 'next-axiom';
import { log, withAxiom } from 'next-axiom';

import { HASURA_TOKEN_MAX_AGE, SESSION_MAX_AGE } from '$/lib/constants';
import { query } from '$/server/common/gql';
Expand Down Expand Up @@ -89,7 +89,7 @@ export default withAxiom(
events: {
async createUser({ user }) {
if (!user.email) {
return console.info('Create an anonymous user');
return log.info('Create an anonymous user');
}
await sendWelcomeLetter({
to: {
Expand Down
4 changes: 2 additions & 2 deletions apps/main/src/pages/api/auth/delete/facebook.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import crypto from 'crypto';
import { NextApiRequest, NextApiResponse } from 'next';
import { withAxiom } from 'next-axiom';
import { log, withAxiom } from 'next-axiom';

import { getApiHandler } from '$/server/common/api-handler';
import { ApiError } from '$/server/common/error';
Expand All @@ -10,7 +10,7 @@ import { DeleteUserDocument } from '$/server/graphql/generated/user';
const handler = getApiHandler();
handler.post(async (req: NextApiRequest, res: NextApiResponse) => {
const signedRequest = req.body.signed_request;
console.log('Validating signature', {
log.debug('Validating signature', {
signedRequest,
});
const [signature, payload] =
Expand Down
2 changes: 1 addition & 1 deletion apps/main/src/pages/blog/[...slug].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export const getStaticProps: GetStaticProps<
if (!params?.slug) {
return { notFound: true };
}
// console.log({ slug: params.slug });
// log.debug({ slug: params.slug });
const [mdxProps, directories] = await Promise.all([
getMDXPropsBySlug([CONTAINER_FOLDER, ...params.slug].join('/')),
getDirectories(CONTAINER_FOLDER, `/${CONTAINER_FOLDER}`),
Expand Down
3 changes: 2 additions & 1 deletion apps/main/src/pages/profile/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { useToast } from '$/components/toast';
import { useCurrentUser } from '$/contexts/current-user-context';
import { useUpdateUserByPkMutation } from '$/graphql/generated/user';
import { useForm } from '$/hooks/use-form';
import { logger } from '$/lib/logger';
import { EMAIL_REGEXP } from '$/utilities/validator';

type FormFields = {
Expand Down Expand Up @@ -75,7 +76,7 @@ export default function Profile(): JSX.Element {
twitterUserName: fields.twitter,
});
if (error) {
console.error(error);
logger.error('Update user profile failed', error);
if (error.message.includes(`unique constraint \"User_email_key\"`)) {
showToast({
type: 'error',
Expand Down
7 changes: 4 additions & 3 deletions apps/main/src/pages/widget/comment/[pageURL].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
GetStaticPropsContext,
GetStaticPaths,
} from 'next';
import { log } from 'next-axiom';
import * as React from 'react';
import superjson from 'superjson';
import { OperationResult } from 'urql';
Expand Down Expand Up @@ -142,7 +143,7 @@ export const getStaticProps: GetStaticProps<
>(
client.subscription(CommentTreeDocument, { pageURL }),
subscribe((result) => {
// console.log(result);
// log.debug(result);
resolve(result);
}),
);
Expand All @@ -160,7 +161,7 @@ export const getStaticProps: GetStaticProps<
'pageByPk',
);
if (!pageByPk) {
console.error(`Can't find theme info`);
log.error(`Can't find theme info`);
return { notFound: true };
}
return {
Expand All @@ -175,7 +176,7 @@ export const getStaticProps: GetStaticProps<
revalidate: 5 * 60,
};
} catch (error) {
console.error(superjson.stringify(error));
log.error(superjson.stringify(error));
return { notFound: true };
}
};
Expand Down
Loading

0 comments on commit 2fcf0e8

Please sign in to comment.