Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
refactor: update logging
Marc Seitz84f7e9834dab
diff --git a/app/api/cron/domains/route.ts b/app/api/cron/domains/route.tsindex 71593350..24e1e555 100644--- a/app/api/cron/domains/route.ts+++ b/app/api/cron/domains/route.ts@@ -113,10 +113,11 @@ export async function POST(req: Request) {);return NextResponse.json(results);} catch (error) {- await log(- `Domains cron failed. Error: " + ${(error as Error).message}`,- true,- );+ await log({+ message: `Domains cron failed. \n\nError: ${(error as Error).message}`,+ type: "cron",+ mention: true+ });return NextResponse.json({ error: (error as Error).message });}}diff --git a/app/api/cron/domains/utils.ts b/app/api/cron/domains/utils.tsindex 63b1ee78..46806daf 100644--- a/app/api/cron/domains/utils.ts+++ b/app/api/cron/domains/utils.ts@@ -19,7 +19,7 @@ export const handleDomainUpdates = async ({linksCount: number;}) => {if (changed) {- await log(`Domain *${domain}* changed status to *${verified}*`, verified);+ await log({message: `Domain *${domain}* changed status to *${verified}*`, type: "cron"});}if (verified) return;@@ -68,10 +68,11 @@ export const handleDomainUpdates = async ({},});if (!team) {- await log(- `Domain *${domain}* is invalid but not associated with any user, skipping.`,- true,- );+ await log({+ message: `Domain *${domain}* is invalid but not associated with any user, skipping.`,+ type: "cron",+ mention: true,+ });return;}@@ -107,19 +108,24 @@ export const handleDomainUpdates = async ({);if (totalLinksViews > 0) {- return await log(- `Domain *${domain}* has been invalid for > 30 days and has links with clicks, skipping.`,- );+ await log({+ message: `Domain *${domain}* has been invalid for > 30 days and has links with clicks, skipping.`,+ type: "cron",+ mention: true+ });+ return;}}// else, delete the domain and send emailreturn await Promise.allSettled([deleteDomain(domain),- log(- `Domain *${domain}* has been invalid for > 30 days and ${+ log({+ message: `Domain *${domain}* has been invalid for > 30 days and ${linksCount > 0 ? "has links but no link clicks" : "has no links"}, deleting.`,- ),+ type: "cron",+ mention: true,+ }),limiter.schedule(() => sendDeletedDomainEmail(userEmail, domain)),]);}@@ -132,9 +138,10 @@ export const handleDomainUpdates = async ({);if (!sentSecondDomainInvalidEmail) {return await Promise.allSettled([- log(- `Domain *${domain}* is invalid for ${invalidDays} days, email sent.`,- ),+ log({+ message: `Domain *${domain}* is invalid for ${invalidDays} days, email sent.`,+ type: "cron",+ }),limiter.schedule(() =>sendInvalidDomainEmail(userEmail, domain, invalidDays),),@@ -158,9 +165,10 @@ export const handleDomainUpdates = async ({);if (!sentFirstDomainInvalidEmail) {return await Promise.allSettled([- log(- `Domain *${domain}* is invalid for ${invalidDays} days, email sent.`,- ),+ log({+ message: `Domain *${domain}* is invalid for ${invalidDays} days, email sent.`,+ type: "cron",+ }),limiter.schedule(() =>sendInvalidDomainEmail(userEmail, domain, invalidDays),),@@ -184,9 +192,10 @@ export const handleDomainUpdates = async ({);if (!sentFirstDayDomainReminderEmail) {return await Promise.allSettled([- log(- `Domain *${domain}* is invalid for ${invalidDays} days, email sent.`,- ),+ log({+ message: `Domain *${domain}* is invalid for ${invalidDays} days, email sent.`,+ type: "cron",+ }),limiter.schedule(() =>sendInvalidDomainEmail(userEmail, domain, invalidDays),),diff --git a/app/api/cron/upgrade/route.ts b/app/api/cron/upgrade/route.tsindex 41e0ea8f..56e69472 100644--- a/app/api/cron/upgrade/route.ts+++ b/app/api/cron/upgrade/route.ts@@ -83,9 +83,10 @@ export async function POST(req: Request) {);if (!sentFirstTrialEndReminderEmail) {return await Promise.allSettled([- log(- `Trial End Reminder for team: *${id}* is expiring in ${teamDaysLeft} days, email sent.`,- ),+ log({+ message: `Trial End Reminder for team: *${id}* is expiring in ${teamDaysLeft} days, email sent.`,+ type: "cron"+ }),limiter.schedule(() =>sendTrialEndReminderEmail(userEmail, userName),),@@ -107,9 +108,10 @@ export async function POST(req: Request) {);if (!sentFinalTrialEndReminderEmail) {return await Promise.allSettled([- log(- `Final Trial End Reminder for team: *${id}* is expiring in ${teamDaysLeft} days, email sent.`,- ),+ log({+ message: `Final Trial End Reminder for team: *${id}* is expiring in ${teamDaysLeft} days, email sent.`,+ type: "cron"+ }),limiter.schedule(() =>sendTrialEndFinalReminderEmail(userEmail, userName),),@@ -127,9 +129,10 @@ export async function POST(req: Request) {// downgrade the user to free if team has 0 day left on trialif (teamDaysLeft <= 0) {return await Promise.allSettled([- log(- `Downgrade to free for user: *${id}* is expiring in ${teamDaysLeft} days, downgraded.`,- ),+ log({+ message: `Downgrade to free for user: *${id}* is expiring in ${teamDaysLeft} days, downgraded.`,+ type: "cron"+ }),prisma.user.update({where: { email: userEmail },data: { plan: "free" },@@ -144,10 +147,11 @@ export async function POST(req: Request) {);return NextResponse.json(results);} catch (error) {- await log(- `Trial end reminder cron failed. Error: " + ${(error as Error).message}`,- true,- );+ await log({+ message:`Trial end reminder cron failed. Error: " + ${(error as Error).message}`,+ type: "cron",+ mention: true,+ });return NextResponse.json({ error: (error as Error).message });}}diff --git a/lib/utils.ts b/lib/utils.tsindex 5d693749..9ce686cb 100644--- a/lib/utils.ts+++ b/lib/utils.ts@@ -43,8 +43,22 @@ export async function fetcher<JSON = any>(return res.json();}-export const log = async (message: string, mention?: boolean) => {- /* Log a message to the console */+export const log = async ({+ message,+ type,+ mention = false,+}: {+ message: string;+ type: "info" | "cron" | "links" | "error";+ mention?: boolean;+}) => {+ /* If in development or env variable not set, log to the console */+ if (process.env.NODE_ENV === "development" || !process.env.PPMK_SLACK_WEBHOOK_URL) {+ console.log(message);+ return;+ }++ /* Log a message to channel */try {return await fetch(`${process.env.PPMK_SLACK_WEBHOOK_URL}`, {method: "POST",@@ -57,7 +71,8 @@ export const log = async (message: string, mention?: boolean) => {type: "section",text: {type: "mrkdwn",- text: `${mention ? "<@U05BTDUKPLZ> " : ""}${message}`,+ // prettier-ignore+ text: `${mention ? "<@U05BTDUKPLZ> " : ""}${type === "error" ? ":rotating_light: " : ""}${message}`,},},],diff --git a/pages/api/links/[id]/visits.ts b/pages/api/links/[id]/visits.tsindex 799b3a3b..430487f9 100644--- a/pages/api/links/[id]/visits.ts+++ b/pages/api/links/[id]/visits.ts@@ -22,6 +22,8 @@ export default async function handle(// get link id from query paramsconst { id } = req.query as { id: string };+ const userId = (session.user as CustomUser).id;+try {// get the numPages from documentconst result = await prisma.link.findUnique({@@ -45,7 +47,7 @@ export default async function handle(});const docId = result?.document.id!;- const userId = (session.user as CustomUser).id;+// check if the the team that own the document has the current userawait getDocumentWithTeamAndUser({docId,@@ -114,7 +116,7 @@ export default async function handle(return res.status(200).json(viewsWithDuration);} catch (error) {- log(`Failed to get views for link ${id}. Error: \n\n ${error}`);+ log({message: `Failed to get views for link: _${id}_. \n\n ${error} \n\n*Metadata*: \`{userId: ${userId}}\``, type: "error"});errorhandler(error, res);}} else {diff --git a/pages/api/links/domains/[...domainSlug].ts b/pages/api/links/domains/[...domainSlug].tsindex 20367fbc..ecab1d59 100644--- a/pages/api/links/domains/[...domainSlug].ts+++ b/pages/api/links/domains/[...domainSlug].ts@@ -1,5 +1,6 @@import { NextApiRequest, NextApiResponse } from "next";import prisma from "@/lib/prisma";+import { log } from "@/lib/utils";export default async function handle(req: NextApiRequest,@@ -7,12 +8,18 @@ export default async function handle() {if (req.method === "GET") {// GET /api/links/domains/:domain/:slug- // GET /api/links/domains/:domainSlugconst { domainSlug } = req.query as { domainSlug: string[] };const domain = domainSlug[0];const slug = domainSlug[1];+ if (slug === "404") {+ return res.status(404).json({+ error: "Link not found",+ message: "link not found",+ });+ }+try {const link = await prisma.link.findUnique({where: {@@ -52,7 +59,9 @@ export default async function handle(},});+ // if link not found, return 404if (!link || !link.document.team) {+ log({message: `Link not found for custom domain _${domain}/${slug}_`, type: "error", mention: true})return res.status(404).json({error: "Link not found",message: `no link found, team ${link?.document.team}`,@@ -61,6 +70,7 @@ export default async function handle(// if owner of document is on free plan, return 404if (link.document.team.plan === "free") {+ log({message: `Link is from a free team _${link.document.team.id}_ for custom domain _${domain}/${slug}_`, type: "info", mention: true})return res.status(404).json({error: "Link not found",message: `link found, team ${link.document.team.plan}`,@@ -83,6 +93,7 @@ export default async function handle(res.status(200).json({ link, brand });} catch (error) {+ log({message: `Cannot get link for custom domain _${domainSlug}_ \n\n${error}`, type: "error", mention: true})return res.status(500).json({message: "Internal Server Error",error: (error as Error).message,diff --git a/pages/api/links/index.ts b/pages/api/links/index.tsindex ef375eae..ca1af7a3 100644--- a/pages/api/links/index.ts+++ b/pages/api/links/index.ts@@ -15,6 +15,7 @@ export default async function handler(req: NextApiRequest,res: NextApiResponse,) {+ // POST /api/linksif (req.method === "POST") {const session = await getServerSession(req, res, authOptions);if (!session) {diff --git a/pages/api/record_view.ts b/pages/api/record_view.tsindex fd1b5538..5d021021 100644--- a/pages/api/record_view.ts+++ b/pages/api/record_view.ts@@ -110,7 +110,7 @@ export default async function handle(res.status(200).json({ message: "View recorded" });} catch (error) {- log(`Failed to record view for ${linkId}. Error: \n\n ${error}`);+ log({message: `Failed to record view (tinybird) for ${linkId}. \n\n ${error}`, type: "error", mention: true});res.status(500).json({ message: (error as Error).message });}}diff --git a/pages/api/stripe/webhook.ts b/pages/api/stripe/webhook.tsindex f6be1c03..de065ef9 100644--- a/pages/api/stripe/webhook.ts+++ b/pages/api/stripe/webhook.ts@@ -69,7 +69,7 @@ export default async function webhookHandler(checkoutSession.client_reference_id === null ||checkoutSession.customer === null) {- await log("Missing items in Stripe webhook callback");+ await log({message: "Missing items in Stripe webhook callback", type: "error"});return;}@@ -171,26 +171,30 @@ export default async function webhookHandler(});if (!team) {- await log(- "Team with stripeId: `" ++ await log({+ message: "Team with stripeId: `" +stripeId +"`not found in Stripe webhook `customer.subscription.deleted` callback",- );+ type: "error"+ });return;}- await log(- ":cry: Team *`" + team.id + "`* deleted their subscription",- );+ await log({+ message: ":cry: Team *`" + team.id + "`* deleted their subscription",+ type: "info"+ });} else {throw new Error("Unhandled relevant event!");}} catch (error) {- await log(- `Stripe webook failed for Event: *${event.type}* (_${+ await log({+ message: `Stripe webook failed for Event: *${event.type}* ([_${event.id- }_) \n\n Error: ${(error as Error).message}`,- );+ }_](https://dashboard.stripe.com/events/${event.id})) \n\n Error: ${(error as Error).message}`,+ type: "error",+ mention: true+ });return;}} else {diff --git a/pages/api/teams/[teamId]/documents/[id]/links.ts b/pages/api/teams/[teamId]/documents/[id]/links.tsindex 6987ca78..828764d4 100644--- a/pages/api/teams/[teamId]/documents/[id]/links.ts+++ b/pages/api/teams/[teamId]/documents/[id]/links.ts@@ -54,7 +54,7 @@ export default async function handle(const links = document!.links;return res.status(200).json(links);} catch (error) {- log(`Failed to get links for document ${docId}. Error: \n\n ${error}`);+ log({message: `Failed to get links for document: _${docId}_. \n\n ${error} \n\n*Metadata*: \`{teamId: ${teamId}, userId: ${userId}}\``, type: "error"});errorhandler(error, res);}} else {diff --git a/pages/api/teams/[teamId]/documents/[id]/versions/index.ts b/pages/api/teams/[teamId]/documents/[id]/versions/index.tsindex 70f5a546..d0a276c5 100644--- a/pages/api/teams/[teamId]/documents/[id]/versions/index.ts+++ b/pages/api/teams/[teamId]/documents/[id]/versions/index.ts@@ -90,9 +90,10 @@ export default async function handle(res.status(200).json({ id: documentId });} catch (error) {- log(- `Failed to create new version for document ${documentId}. Error: \n\n ${error}`,- );+ log({+ message: `Failed to create new version for document: _${documentId}_. \n\n ${error} \n\n*Metadata*: \`{teamId: ${teamId}, userId: ${userId}}\``,+ type: "error",+ });return res.status(500).json({message: "Internal Server Error",error: (error as Error).message,diff --git a/pages/api/teams/[teamId]/documents/[id]/views/index.ts b/pages/api/teams/[teamId]/documents/[id]/views/index.tsindex 431f75a5..ee41446e 100644--- a/pages/api/teams/[teamId]/documents/[id]/views/index.ts+++ b/pages/api/teams/[teamId]/documents/[id]/views/index.ts@@ -1,6 +1,5 @@import { NextApiRequest, NextApiResponse } from "next";import { getServerSession } from "next-auth/next";-import prisma from "@/lib/prisma";import { log } from "@/lib/utils";import { getViewPageDuration } from "@/lib/tinybird";import { authOptions } from "@/pages/api/auth/[...nextauth]";@@ -100,7 +99,7 @@ export default async function handle(return res.status(200).json(viewsWithDuration);} catch (error) {- log(`Failed to get views for link ${docId}. Error: \n\n ${error}`);+ log({message: `Failed to get views for document: _${docId}_. \n\n ${error} \n\n*Metadata*: \`{teamId: ${teamId}, userId: ${userId}}\``, type: "error"});errorhandler(error, res);}} else {diff --git a/pages/api/teams/[teamId]/documents/index.ts b/pages/api/teams/[teamId]/documents/index.tsindex d7e8447c..c690304f 100644--- a/pages/api/teams/[teamId]/documents/index.ts+++ b/pages/api/teams/[teamId]/documents/index.ts@@ -161,9 +161,10 @@ export default async function handle(return res.status(201).json(document);} catch (error) {- log(- `Failed to create document. \n\n teamId: ${teamId}, file: ${fileUrl} \n\n ${error}`,- );+ log({+ message: `Failed to create document. \n\n*teamId*: _${teamId}_, \n\n*file*: ${fileUrl} \n\n ${error}`,+ type: "error",+ });errorhandler(error, res);}} else {diff --git a/pages/api/teams/[teamId]/documents/update.ts b/pages/api/teams/[teamId]/documents/update.tsindex e5a1a918..9fa2ef53 100644--- a/pages/api/teams/[teamId]/documents/update.ts+++ b/pages/api/teams/[teamId]/documents/update.ts@@ -49,7 +49,7 @@ export default async function handle(return res.status(201).json({ message: "Document updated successfully" });} catch (error) {- log(`Failed to update document: ${documentId}. Error: \n\n ${error}`);+ log({message: `Failed to update document: _${documentId}_. \n\n ${error} \n\n*Metadata*: \`{teamId: ${teamId}, userId: ${userId}}\``, type: "error"});errorhandler(error, res);}} else {diff --git a/pages/api/teams/[teamId]/domains/[domain]/index.ts b/pages/api/teams/[teamId]/domains/[domain]/index.tsindex 4aac5198..b7112cf7 100644--- a/pages/api/teams/[teamId]/domains/[domain]/index.ts+++ b/pages/api/teams/[teamId]/domains/[domain]/index.ts@@ -63,7 +63,7 @@ export default async function handle(return res.status(204).end(); // 204 No Content response for successful deletes} catch (error) {- log(`Failed to delete domain: ${domain}. Error: \n\n ${error}`);+ log({message: `Failed to delete domain: _${domain}_. \n\n ${error} \n\n*Metadata*: \`{teamId: ${teamId}, userId: ${userId}}\``, type: "error", mention: true});errorhandler(error, res);}} else {diff --git a/pages/api/teams/[teamId]/domains/index.ts b/pages/api/teams/[teamId]/domains/index.tsindex 54008eca..13ab9da9 100644--- a/pages/api/teams/[teamId]/domains/index.ts+++ b/pages/api/teams/[teamId]/domains/index.ts@@ -90,7 +90,7 @@ export default async function handle(return res.status(201).json(response);} catch (error) {- log(`Failed to add domain. Error: \n\n ${error}`);+ log({message: `Failed to add domain. \n\n ${error} \n\n*Metadata*: \`{teamId: ${teamId}, userId: ${userId}}\``, type: "error", mention: true});errorhandler(error, res);}} else {diff --git a/pages/api/teams/index.ts b/pages/api/teams/index.tsindex f6f724f0..a9a389fe 100644--- a/pages/api/teams/index.ts+++ b/pages/api/teams/index.ts@@ -64,7 +64,7 @@ export default async function handle(return res.status(200).json(teams);} catch (error) {- log(`Failed to find team for user: ${user.id} \n\n ${error}`);+ log({message: `Failed to find team for user: _${user.id}_ \n\n ${error}`, type: "error"});errorhandler(error, res);}} else if (req.method === "POST") {@@ -96,7 +96,7 @@ export default async function handle(return res.status(201).json(newTeam);} catch (error) {- log(`Failed to create team "${team}" for user: ${user.id}. Error: \n\n ${error}`);+ log({message: `Failed to create team "${team}" for user: _${user.id}_. \n\n*Error*: \n\n ${error}`, type: "error"});errorhandler(error, res);}} else {diff --git a/pages/api/views.ts b/pages/api/views.tsindex baad69ed..d83ffc1a 100644--- a/pages/api/views.ts+++ b/pages/api/views.ts@@ -247,7 +247,7 @@ export default async function handle(return res.status(200).json(returnObject);} catch (error) {- log(`Failed to record view for ${linkId}. Error: \n\n ${error}`);+ log({message: `Failed to record view for ${linkId}. \n\n ${error}`, type: "error", mention: true});return res.status(500).json({ message: (error as Error).message });}}diff --git a/pages/view/domains/[domain]/[slug]/index.tsx b/pages/view/domains/[domain]/[slug]/index.tsxindex 740443fe..311d0ffc 100644--- a/pages/view/domains/[domain]/[slug]/index.tsx+++ b/pages/view/domains/[domain]/[slug]/index.tsx@@ -11,6 +11,7 @@ import notion from "@/lib/notion";import { parsePageId } from "notion-utils";import { Brand } from "@prisma/client";import CustomMetatag from "@/components/view/custom-metatag";+import { log } from "@/lib/utils";export const getStaticProps = async (context: GetStaticPropsContext) => {const { domain, slug } = context.params as { domain: string; slug: string };