Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: add axiom logs #481

Merged
merged 3 commits into from
Aug 27, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Next.js: debug server-side",
"type": "node-terminal",
"request": "launch",
"command": "npm run dev",
"cwd": "${workspaceFolder}/apps/main"
},
{
"type": "node",
"request": "attach",
Expand Down
2 changes: 2 additions & 0 deletions apps/main/next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const withBundleAnalyzer = require('@next/bundle-analyzer')({
});
const { withPlausibleProxy } = require('next-plausible');
const { RelativeCiAgentWebpackPlugin } = require('@relative-ci/agent');
const { withAxiom } = require('next-axiom');

const analyticsDomain = process.env.NEXT_PUBLIC_ANALYTICS_DOMAIN;
const isProd = process.env.NODE_ENV === 'production';
Expand All @@ -14,6 +15,7 @@ const isProd = process.env.NODE_ENV === 'production';
**/
module.exports = withPlugins(
[
[withAxiom],
[withBundleAnalyzer],
[
withPlausibleProxy({
Expand Down
1 change: 1 addition & 0 deletions apps/main/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
"lodash": "4.17.21",
"next": "12.2.5",
"next-auth": "4.10.3",
"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
19 changes: 12 additions & 7 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 @@ -35,14 +36,18 @@ export function registerNotificationSubscription(): Promise<Response | void> {
'Content-type': 'application/json',
},
body: JSON.stringify({ subscription }),
}).then((rsp) => {
sessionStorage.setItem(NOTIFICATION_DID_REGISTER_KEY, 'true');
return rsp;
});
})
.then((rsp) => {
sessionStorage.setItem(NOTIFICATION_DID_REGISTER_KEY, 'true');
return rsp;
})
.catch((error) => {
logger.warn('Register notification subscription', error);
});
});
})
.catch((error) => {
console.error('Service worker registration failed', error);
logger.error('Service worker registration failed', error);
throw error;
});
}
Expand All @@ -51,7 +56,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 +65,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' });
31 changes: 17 additions & 14 deletions apps/main/src/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
import { withAuth } from 'next-auth/middleware';
import { withAxiom } from 'next-axiom';

export default withAuth({
callbacks: {
authorized: ({ token, req }) => {
if (req.nextUrl.pathname.includes('/api/mutation-event')) {
// We add a custom secret to verify the hasura event callback requests
return (
req.headers.get('hasura_event_secret') ===
process.env.HASURA_EVENT_SECRET
);
}
// Anonymous user doesn't have an email address
return !!(token?.email || token?.name);
export default withAxiom(
withAuth({
callbacks: {
authorized: ({ token, req }) => {
if (req.nextUrl.pathname.includes('/api/mutation-event')) {
// We add a custom secret to verify the hasura event callback requests
return (
req.headers.get('hasura_event_secret') ===
process.env.HASURA_EVENT_SECRET
);
}
// Anonymous user doesn't have an email address
return !!(token?.email || token?.name);
},
},
},
});
}),
);

export const config = {
matcher: [
Expand Down
20 changes: 1 addition & 19 deletions apps/main/src/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { SessionProvider } from 'next-auth/react';
import PlausibleProvider from 'next-plausible';
import { ThemeProvider as NextThemesProvider } from 'next-themes';
import type { AppProps } from 'next/app';
import { NextWebVitalsMetric } from 'next/app';
import * as React from 'react';

import { ToastProvider } from '$/components/toast';
Expand Down Expand Up @@ -51,24 +50,7 @@ function App({

export default App;

export function reportWebVitals(metric: NextWebVitalsMetric) {
const url = process.env.NEXT_PUBLIC_AXIOM_INGEST_ENDPOINT;

if (!url) {
return;
}

const body = JSON.stringify({
route: window.__NEXT_DATA__.page,
...metric,
});

if (navigator.sendBeacon) {
navigator.sendBeacon(url, body);
} else {
fetch(url, { body, method: 'POST', keepalive: true });
}
}
export { reportWebVitals } from 'next-axiom/dist/webVitals';

export const loadFeatures = () =>
import(
Expand Down
Loading