Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

Enhance logging across API endpoints and integrate request logging

Bill Yangd3fc525ecbfc
diff --git a/server/src/api/admin/adminMoveSite.ts b/server/src/api/admin/adminMoveSite.ts
index a668862e0..8872c58ea 100644
--- a/server/src/api/admin/adminMoveSite.ts
+++ b/server/src/api/admin/adminMoveSite.ts
@@ -51,7 +51,7 @@ export async function adminMoveSite(
return reply.status(200).send({ success: true, organizationId: targetOrganizationId });
} catch (error) {
- console.error("Error moving site (admin):", error);
+ request.log.error({ err: error }, "Error moving site (admin)");
return reply.status(500).send({ error: "Failed to move site" });
}
}
diff --git a/server/src/api/admin/collectTelemetry.ts b/server/src/api/admin/collectTelemetry.ts
index a7617ea4e..2278b0c88 100644
--- a/server/src/api/admin/collectTelemetry.ts
+++ b/server/src/api/admin/collectTelemetry.ts
@@ -37,7 +37,7 @@ export async function collectTelemetry(
return reply.send({ success: true });
} catch (error) {
- console.error("Error collecting telemetry:", error);
+ request.log.error({ err: error }, "Error collecting telemetry");
return reply.status(500).send({ error: "Failed to collect telemetry" });
}
}
diff --git a/server/src/api/admin/getAdminOrganizations.ts b/server/src/api/admin/getAdminOrganizations.ts
index e6658f78d..0954996c3 100644
--- a/server/src/api/admin/getAdminOrganizations.ts
+++ b/server/src/api/admin/getAdminOrganizations.ts
@@ -4,7 +4,6 @@ import { DateTime } from "luxon";
import { clickhouse } from "../../db/clickhouse/clickhouse.js";
import { db } from "../../db/postgres/postgres.js";
import { member, sites, user } from "../../db/postgres/schema.js";
-import { logger } from "../../lib/logger/logger.js";
import { getOrganizationSubscriptions } from "../../services/admin/subscriptionService.js";
interface EventCountResult {
@@ -149,7 +148,7 @@ export async function getAdminOrganizations(request: FastifyRequest, reply: Fast
siteEventMap30d.set(Number(event.site_id), event.total_events);
}
} catch (clickhouseError) {
- logger.warn(clickhouseError as Error, "ClickHouse query failed, continuing without event counts");
+ request.log.warn(clickhouseError as Error, "ClickHouse query failed, continuing without event counts");
}
// Create map of organization IDs to their sites with event counts
@@ -191,7 +190,7 @@ export async function getAdminOrganizations(request: FastifyRequest, reply: Fast
return reply.status(200).send(enrichedOrganizations);
} catch (error) {
- console.error("Get Admin Organizations Error:", error);
+ request.log.error({ err: error }, "Get Admin Organizations Error");
return reply.status(500).send({
error: "Failed to fetch organizations data",
details: error instanceof Error ? error.message : "Unknown error",
diff --git a/server/src/api/admin/getAdminServiceEventCount.ts b/server/src/api/admin/getAdminServiceEventCount.ts
index 6747e4f1f..67dbd19d2 100644
--- a/server/src/api/admin/getAdminServiceEventCount.ts
+++ b/server/src/api/admin/getAdminServiceEventCount.ts
@@ -89,7 +89,7 @@ export async function getAdminServiceEventCount(
const data = await processResults<ServiceEventCountResponse[number]>(result);
return res.send({ data });
} catch (error) {
- console.error("Error fetching service event count:", error);
+ req.log.error({ err: error }, "Error fetching service event count");
return res.status(500).send({ error: "Failed to fetch service event count" });
}
}
diff --git a/server/src/api/analytics/dashboards/createDashboard.ts b/server/src/api/analytics/dashboards/createDashboard.ts
index 818a7507a..8fa0a0ac6 100644
--- a/server/src/api/analytics/dashboards/createDashboard.ts
+++ b/server/src/api/analytics/dashboards/createDashboard.ts
@@ -39,7 +39,7 @@ export async function createDashboard(
if (error instanceof z.ZodError) {
return reply.status(400).send({ error: "Validation error", details: error.errors });
}
- console.error("Error creating dashboard:", error);
+ request.log.error({ err: error }, "Error creating dashboard");
return reply.status(500).send({ error: "Failed to create dashboard" });
}
}
diff --git a/server/src/api/analytics/dashboards/deleteDashboard.ts b/server/src/api/analytics/dashboards/deleteDashboard.ts
index 9b528b968..f1583a3ad 100644
--- a/server/src/api/analytics/dashboards/deleteDashboard.ts
+++ b/server/src/api/analytics/dashboards/deleteDashboard.ts
@@ -47,7 +47,7 @@ export async function deleteDashboard(
return reply.send({ success: true });
} catch (error) {
- console.error("Error deleting dashboard:", error);
+ request.log.error({ err: error }, "Error deleting dashboard");
return reply.status(500).send({ error: "Failed to delete dashboard" });
}
}
diff --git a/server/src/api/analytics/dashboards/getDashboard.ts b/server/src/api/analytics/dashboards/getDashboard.ts
index 0e07f4d4e..348eecfdf 100644
--- a/server/src/api/analytics/dashboards/getDashboard.ts
+++ b/server/src/api/analytics/dashboards/getDashboard.ts
@@ -37,7 +37,7 @@ export async function getDashboard(
return reply.send(dashboard);
} catch (error) {
- console.error("Error fetching dashboard:", error);
+ request.log.error({ err: error }, "Error fetching dashboard");
return reply.status(500).send({ error: "Failed to fetch dashboard" });
}
}
diff --git a/server/src/api/analytics/dashboards/getDashboards.ts b/server/src/api/analytics/dashboards/getDashboards.ts
index 473f51115..13d2fb801 100644
--- a/server/src/api/analytics/dashboards/getDashboards.ts
+++ b/server/src/api/analytics/dashboards/getDashboards.ts
@@ -24,7 +24,7 @@ export async function getDashboards(
return reply.send(siteDashboards);
} catch (error) {
- console.error("Error fetching dashboards:", error);
+ request.log.error({ err: error }, "Error fetching dashboards");
return reply.status(500).send({ error: "Failed to fetch dashboards" });
}
}
diff --git a/server/src/api/analytics/dashboards/updateDashboard.ts b/server/src/api/analytics/dashboards/updateDashboard.ts
index d6de1166c..e718af441 100644
--- a/server/src/api/analytics/dashboards/updateDashboard.ts
+++ b/server/src/api/analytics/dashboards/updateDashboard.ts
@@ -56,7 +56,7 @@ export async function updateDashboard(
if (error instanceof z.ZodError) {
return reply.status(400).send({ error: "Validation error", details: error.errors });
}
- console.error("Error updating dashboard:", error);
+ request.log.error({ err: error }, "Error updating dashboard");
return reply.status(500).send({ error: "Failed to update dashboard" });
}
}
diff --git a/server/src/api/analytics/funnels/createFunnel.ts b/server/src/api/analytics/funnels/createFunnel.ts
index 8b6a812a8..58e147aa7 100644
--- a/server/src/api/analytics/funnels/createFunnel.ts
+++ b/server/src/api/analytics/funnels/createFunnel.ts
@@ -103,7 +103,7 @@ export async function createFunnel(
funnelId: result[0].reportId,
});
} catch (error) {
- console.error("Error creating funnel:", error);
+ request.log.error({ err: error }, "Error creating funnel");
return reply.status(500).send({ error: "Failed to create funnel" });
}
}
diff --git a/server/src/api/analytics/funnels/deleteFunnel.ts b/server/src/api/analytics/funnels/deleteFunnel.ts
index a3902bb28..91ecb0ac8 100644
--- a/server/src/api/analytics/funnels/deleteFunnel.ts
+++ b/server/src/api/analytics/funnels/deleteFunnel.ts
@@ -54,7 +54,7 @@ export async function deleteFunnel(
return reply.status(200).send({ success: true });
} catch (error) {
- console.error("Error deleting funnel:", error);
+ request.log.error({ err: error }, "Error deleting funnel");
return reply.status(500).send({ error: "Failed to delete funnel" });
}
}
diff --git a/server/src/api/analytics/funnels/getFunnel.ts b/server/src/api/analytics/funnels/getFunnel.ts
index 976de1614..d6a664804 100644
--- a/server/src/api/analytics/funnels/getFunnel.ts
+++ b/server/src/api/analytics/funnels/getFunnel.ts
@@ -141,12 +141,12 @@ export async function getFunnel(
return reply.send({ data });
} catch (error) {
if (error instanceof AnalyticsQueryError) {
- console.error("Error executing funnel query:", error.original);
+ request.log.error({ err: error.original }, "Error executing funnel query");
for (const query of error.queries) {
- console.error("Failed query:", query);
+ request.log.debug({ query }, "Failed funnel query");
}
} else {
- console.error("Error executing funnel query:", error);
+ request.log.error({ err: error }, "Error executing funnel query");
}
return reply.status(500).send({ error: "Failed to execute funnel analysis" });
}
diff --git a/server/src/api/analytics/funnels/getFunnels.ts b/server/src/api/analytics/funnels/getFunnels.ts
index 9f3a859aa..229eb368f 100644
--- a/server/src/api/analytics/funnels/getFunnels.ts
+++ b/server/src/api/analytics/funnels/getFunnels.ts
@@ -39,7 +39,7 @@ export async function getFunnels(
return reply.send({ data: funnels });
} catch (error) {
- console.error("Error fetching funnels:", error);
+ request.log.error({ err: error }, "Error fetching funnels");
return reply.status(500).send({ error: "Failed to fetch funnels" });
}
}
diff --git a/server/src/api/analytics/generatePdfReport.ts b/server/src/api/analytics/generatePdfReport.ts
index ef5bff6ea..cabaa345f 100644
--- a/server/src/api/analytics/generatePdfReport.ts
+++ b/server/src/api/analytics/generatePdfReport.ts
@@ -102,7 +102,7 @@ export async function generatePdfReport(request: FastifyRequest<GeneratePdfRepor
.header("Content-Disposition", `attachment; filename="${filename}"`)
.send(pdfBuffer);
} catch (error) {
- console.error("Error generating PDF report:", error);
+ request.log.error({ err: error }, "Error generating PDF report");
if (error instanceof Error && error.message.includes("not found")) {
return reply.status(404).send({ error: error.message });
diff --git a/server/src/api/analytics/getErrorBucketed.ts b/server/src/api/analytics/getErrorBucketed.ts
index aba98c669..f46fbd396 100644
--- a/server/src/api/analytics/getErrorBucketed.ts
+++ b/server/src/api/analytics/getErrorBucketed.ts
@@ -106,7 +106,10 @@ export async function getErrorBucketed(req: FastifyRequest<GetErrorBucketedReque
data: data,
});
} catch (error) {
- console.error("Error getting error bucketed data:", error instanceof AnalyticsQueryError ? error.original : error);
+ req.log.error(
+ { err: error instanceof AnalyticsQueryError ? error.original : error },
+ "Error getting error bucketed data"
+ );
return res.status(500).send({
success: false,
error: "Failed to get error data",
diff --git a/server/src/api/analytics/getJourneys.ts b/server/src/api/analytics/getJourneys.ts
index af5bff118..99024281d 100644
--- a/server/src/api/analytics/getJourneys.ts
+++ b/server/src/api/analytics/getJourneys.ts
@@ -151,7 +151,7 @@ export const getJourneys = async (request: FastifyRequest<GetJourneysRequest>, r
})),
});
} catch (error) {
- console.error("Error getting journeys:", error instanceof AnalyticsQueryError ? error.original : error);
+ request.log.error({ err: error instanceof AnalyticsQueryError ? error.original : error }, "Error getting journeys");
return reply.status(500).send({ error: "Failed to get journeys" });
}
};
diff --git a/server/src/api/analytics/goals/createGoal.ts b/server/src/api/analytics/goals/createGoal.ts
index 2cf35c561..35ea5f286 100644
--- a/server/src/api/analytics/goals/createGoal.ts
+++ b/server/src/api/analytics/goals/createGoal.ts
@@ -49,7 +49,7 @@ export async function createGoal(
goalId: result[0].goalId,
});
} catch (error) {
- console.error("Error creating goal:", error);
+ request.log.error({ err: error }, "Error creating goal");
// Handle validation errors
if (error instanceof z.ZodError) {
diff --git a/server/src/api/analytics/goals/deleteGoal.ts b/server/src/api/analytics/goals/deleteGoal.ts
index 6776a847b..299710738 100644
--- a/server/src/api/analytics/goals/deleteGoal.ts
+++ b/server/src/api/analytics/goals/deleteGoal.ts
@@ -55,7 +55,7 @@ export async function deleteGoal(
return reply.send({ success: true });
} catch (error) {
- console.error("Error deleting goal:", error);
+ request.log.error({ err: error }, "Error deleting goal");
return reply.status(500).send({ error: "Failed to delete goal" });
}
}
diff --git a/server/src/api/analytics/goals/updateGoal.ts b/server/src/api/analytics/goals/updateGoal.ts
index 9137b4ee1..0dffb7797 100644
--- a/server/src/api/analytics/goals/updateGoal.ts
+++ b/server/src/api/analytics/goals/updateGoal.ts
@@ -69,7 +69,7 @@ export async function updateGoal(
goalId: result[0].goalId,
});
} catch (error) {
- console.error("Error updating goal:", error);
+ request.log.error({ err: error }, "Error updating goal");
// Handle validation errors
if (error instanceof z.ZodError) {
diff --git a/server/src/api/analytics/users/deleteUser.ts b/server/src/api/analytics/users/deleteUser.ts
index 486f3ae28..abca880b6 100644
--- a/server/src/api/analytics/users/deleteUser.ts
+++ b/server/src/api/analytics/users/deleteUser.ts
@@ -58,7 +58,7 @@ export async function deleteUser(req: FastifyRequest<DeleteUserRequest>, res: Fa
const r2Keys = await processResults<{ event_data_key: string }>(r2KeysResult);
await Promise.all(r2Keys.map(row => r2Storage.deleteBatch(row.event_data_key)));
} catch (error) {
- console.error(`Failed to delete R2 replay data for user ${userId}:`, error);
+ req.log.error({ err: error }, `Failed to delete R2 replay data for user ${userId}:`);
}
}
@@ -82,7 +82,7 @@ export async function deleteUser(req: FastifyRequest<DeleteUserRequest>, res: Fa
return res.send({ success: true });
} catch (error) {
- console.error("Error deleting user:", error);
+ req.log.error({ err: error }, "Error deleting user");
return res.status(500).send({ error: "Failed to delete user" });
}
}
diff --git a/server/src/api/analytics/users/getUserInfo.ts b/server/src/api/analytics/users/getUserInfo.ts
index d36afe7f5..2e42088d6 100644
--- a/server/src/api/analytics/users/getUserInfo.ts
+++ b/server/src/api/analytics/users/getUserInfo.ts
@@ -326,7 +326,7 @@ export async function getUserInfo(
},
});
} catch (error) {
- console.error("Error fetching user info:", error);
+ req.log.error({ err: error }, "Error fetching user info");
return res.status(500).send({
error: "Internal server error",
});
diff --git a/server/src/api/analytics/users/identifyUser.ts b/server/src/api/analytics/users/identifyUser.ts
index 652f543f9..69496d144 100644
--- a/server/src/api/analytics/users/identifyUser.ts
+++ b/server/src/api/analytics/users/identifyUser.ts
@@ -83,7 +83,7 @@ export async function identifyUser(req: FastifyRequest<IdentifyUserRequest>, res
return res.send({ success: true });
} catch (error) {
- console.error("Error identifying user:", error);
+ req.log.error({ err: error }, "Error identifying user");
return res.status(500).send({ error: "Failed to identify user" });
}
}
diff --git a/server/src/api/analytics/users/updateUserTraits.ts b/server/src/api/analytics/users/updateUserTraits.ts
index 7bc37a1f0..48e9a8db5 100644
--- a/server/src/api/analytics/users/updateUserTraits.ts
+++ b/server/src/api/analytics/users/updateUserTraits.ts
@@ -56,7 +56,7 @@ export async function updateUserTraits(req: FastifyRequest<UpdateUserTraitsReque
return res.send({ success: true });
} catch (error) {
- console.error("Error updating user traits:", error);
+ req.log.error({ err: error }, "Error updating user traits");
return res.status(500).send({ error: "Failed to update user traits" });
}
}
diff --git a/server/src/api/analytics/utils/analyticsQuery.test.ts b/server/src/api/analytics/utils/analyticsQuery.test.ts
index 42ff966e8..3dbd8827f 100644
--- a/server/src/api/analytics/utils/analyticsQuery.test.ts
+++ b/server/src/api/analytics/utils/analyticsQuery.test.ts
@@ -19,6 +19,10 @@ import {
const mockQuery = vi.mocked(clickhouse.query);
const resultSet = (rows: unknown[]) => ({ json: async () => rows }) as any;
+const requestLog = {
+ debug: vi.fn(),
+ error: vi.fn(),
+};
const mockRes = () => {
const res: any = {};
@@ -122,28 +126,29 @@ describe("analyticsRoute", () => {
const res = mockRes();
const handler = analyticsRoute("things", async (_req, reply) => reply.send({ data: [1] }));
- await handler({} as any, res);
+ await handler({ log: requestLog } as any, res);
expect(res.send).toHaveBeenCalledWith({ data: [1] });
expect(res.status).not.toHaveBeenCalled();
});
it("maps errors to a 500 with the label", async () => {
- const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
const res = mockRes();
const handler = analyticsRoute("things", async () => {
throw new Error("boom");
});
- await handler({} as any, res);
+ await handler({ log: requestLog } as any, res);
expect(res.status).toHaveBeenCalledWith(500);
expect(res.send).toHaveBeenCalledWith({ error: "Failed to fetch things" });
- consoleError.mockRestore();
+ expect(requestLog.error).toHaveBeenCalledWith(
+ { err: expect.any(Error), label: "things" },
+ "Analytics query failed"
+ );
});
it("derives the label from the request and logs failed SQL", async () => {
- const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
const res = mockRes();
const handler = analyticsRoute<{ Querystring: { parameter: string } }>(
req => req.query.parameter,
@@ -152,10 +157,9 @@ describe("analyticsRoute", () => {
}
);
- await handler({ query: { parameter: "browser" } } as any, res);
+ await handler({ query: { parameter: "browser" }, log: requestLog } as any, res);
expect(res.send).toHaveBeenCalledWith({ error: "Failed to fetch browser" });
- expect(consoleError).toHaveBeenCalledWith("Failed query:", "SELECT bad");
- consoleError.mockRestore();
+ expect(requestLog.debug).toHaveBeenCalledWith({ query: "SELECT bad" }, "Failed analytics query");
});
});
diff --git a/server/src/api/analytics/utils/analyticsQuery.ts b/server/src/api/analytics/utils/analyticsQuery.ts
index 341b10822..41fff6245 100644
--- a/server/src/api/analytics/utils/analyticsQuery.ts
+++ b/server/src/api/analytics/utils/analyticsQuery.ts
@@ -104,12 +104,12 @@ export function analyticsRoute<R extends RouteGenericInterface>(
} catch (error) {
const label = typeof errorLabel === "function" ? errorLabel(req) : errorLabel;
if (error instanceof AnalyticsQueryError) {
- console.error(`Error fetching ${label}:`, error.original);
+ req.log.error({ err: error.original, label }, "Analytics query failed");
for (const query of error.queries) {
- console.error("Failed query:", query);
+ req.log.debug({ query }, "Failed analytics query");
}
} else {
- console.error(`Error fetching ${label}:`, error);
+ req.log.error({ err: error, label }, "Analytics query failed");
}
return res.status(500).send({ error: `Failed to fetch ${label}` });
}
diff --git a/server/src/api/as/activate.ts b/server/src/api/as/activate.ts
index 9b1332458..4121745d2 100644
--- a/server/src/api/as/activate.ts
+++ b/server/src/api/as/activate.ts
@@ -9,11 +9,7 @@ import { IS_CLOUD } from "../../lib/const.js";
* Check if AppSumo integration is enabled
*/
function isAppSumoEnabled(): boolean {
- return (
- IS_CLOUD &&
- !!process.env.APPSUMO_CLIENT_ID &&
- !!process.env.APPSUMO_CLIENT_SECRET
- );
+ return IS_CLOUD && !!process.env.APPSUMO_CLIENT_ID && !!process.env.APPSUMO_CLIENT_SECRET;
}
/**
@@ -127,7 +123,7 @@ export async function activateAppSumoLicense(
try {
tokenData = await exchangeCodeForToken(code);
} catch (error) {
- console.error("Error exchanging code for token:", error);
+ request.log.error({ err: error }, "Error exchanging code for token");
return reply.status(400).send({
error: "Failed to exchange authorization code",
message: error instanceof Error ? error.message : "Unknown error",
@@ -139,7 +135,7 @@ export async function activateAppSumoLicense(
try {
licenseData = await fetchLicenseKey(tokenData.accessToken);
} catch (error) {
- console.error("Error fetching license key:", error);
+ request.log.error({ err: error }, "Error fetching license key");
return reply.status(400).send({
error: "Failed to fetch license key",
message: error instanceof Error ? error.message : "Unknown error",
@@ -204,7 +200,7 @@ export async function activateAppSumoLicense(
},
});
} catch (error) {
- console.error("Error activating AppSumo license:", error);
+ request.log.error({ err: error }, "Error activating AppSumo license");
return reply.status(500).send({
error: "Internal server error",
message: error instanceof Error ? error.message : "Unknown error",
diff --git a/server/src/api/as/webhook.test.ts b/server/src/api/as/webhook.test.ts
index 24be47c09..af318236a 100644
--- a/server/src/api/as/webhook.test.ts
+++ b/server/src/api/as/webhook.test.ts
@@ -16,17 +16,17 @@ vi.mock("../../lib/const.js", () => ({
IS_CLOUD: true,
}));
-vi.mock("../../lib/logger/logger.js", () => ({
- logger: {
- info: mocks.loggerInfo,
- warn: mocks.loggerWarn,
- error: mocks.loggerError,
- },
-}));
-
import { handleAppSumoWebhook } from "./webhook.js";
const dialect = new PgDialect();
+const requestLogger: any = {
+ debug: vi.fn(),
+ error: mocks.loggerError,
+ info: mocks.loggerInfo,
+ warn: mocks.loggerWarn,
+ child: vi.fn(),
+};
+requestLogger.child.mockReturnValue(requestLogger);
// Renders the drizzle sql`` object passed to db.execute on the nth call into
// { sql, params } so we can assert the intended statement and bind values.
@@ -35,7 +35,7 @@ function executedQuery(n: number) {
}
function createRequest(body: Record<string, unknown>) {
- return { body } as any;
+ return { body, log: requestLogger } as any;
}
function createReply() {
diff --git a/server/src/api/as/webhook.ts b/server/src/api/as/webhook.ts
index 1faa76143..ea448059b 100644
--- a/server/src/api/as/webhook.ts
+++ b/server/src/api/as/webhook.ts
@@ -1,8 +1,8 @@
import { sql } from "drizzle-orm";
import { FastifyReply, FastifyRequest } from "fastify";
+import type { FastifyBaseLogger } from "fastify";
import { db } from "../../db/postgres/postgres.js";
import { IS_CLOUD } from "../../lib/const.js";
-import { logger } from "../../lib/logger/logger.js";
interface AppSumoWebhookPayload {
test?: boolean;
@@ -55,19 +55,21 @@ export async function handleAppSumoWebhook(
}>,
reply: FastifyReply
) {
+ const requestLogger = request.log.child({ integration: "appsumo" });
+
if (!isAppSumoEnabled()) {
- logger.info("[AppSumo] Integration not enabled");
+ requestLogger.info("[AppSumo] Integration not enabled");
return reply.status(503).send({
error: "AppSumo integration is not available",
});
}
const payload = request.body;
- logger.info({ payload }, "[AppSumo] Received webhook");
+ requestLogger.info({ payload }, "[AppSumo] Received webhook");
// Handle test webhook for AppSumo validation
if (payload.test === true || payload.event === "test") {
- logger.info("[AppSumo] Test webhook received");
+ requestLogger.info("[AppSumo] Test webhook received");
return reply.status(200).send({
event: "test",
success: true,
@@ -81,7 +83,7 @@ export async function handleAppSumoWebhook(
const { license_key, event, tier, parent_license_key, prev_license_key, license_status, event_timestamp, extra } =
payload;
- logger.info(`[AppSumo] Processing ${event} event for license ${license_key}`);
+ requestLogger.info(`[AppSumo] Processing ${event} event for license ${license_key}`);
// Log webhook event for audit trail
await db.execute(sql`
@@ -105,31 +107,31 @@ export async function handleAppSumoWebhook(
case "purchase":
// License purchased - create placeholder record
// Note: license_status will be "inactive" until user activates
- logger.info(`[AppSumo] Handling purchase event for license ${license_key}, tier ${tier}`);
- await handlePurchaseEvent(license_key, tier, parent_license_key);
+ requestLogger.info(`[AppSumo] Handling purchase event for license ${license_key}, tier ${tier}`);
+ await handlePurchaseEvent(requestLogger, license_key, tier, parent_license_key);
break;
case "activate":
// License activated by user
// Note: license_status is "inactive" in webhook, becomes active after our 200 response
- logger.info(`[AppSumo] Handling activate event for license ${license_key}, tier ${tier}`);
- await handleActivateEvent(license_key, tier);
+ requestLogger.info(`[AppSumo] Handling activate event for license ${license_key}, tier ${tier}`);
+ await handleActivateEvent(requestLogger, license_key, tier);
break;
case "upgrade":
// License upgraded to higher tier
// Note: Creates NEW license_key with prev_license_key pointing to old one
// AppSumo sends simultaneous deactivate event for old license (we skip it)
- logger.info(`[AppSumo] Handling upgrade event: ${prev_license_key} -> ${license_key}, tier ${tier}`);
- await handleUpgradeEvent(license_key, tier, prev_license_key);
+ requestLogger.info(`[AppSumo] Handling upgrade event: ${prev_license_key} -> ${license_key}, tier ${tier}`);
+ await handleUpgradeEvent(requestLogger, license_key, tier, prev_license_key);
break;
case "downgrade":
// License downgraded to lower tier
// Note: Creates NEW license_key with prev_license_key pointing to old one
// AppSumo sends simultaneous deactivate event for old license (we skip it)
- logger.info(`[AppSumo] Handling downgrade event: ${prev_license_key} -> ${license_key}, tier ${tier}`);
- await handleDowngradeEvent(license_key, tier, prev_license_key);
+ requestLogger.info(`[AppSumo] Handling downgrade event: ${prev_license_key} -> ${license_key}, tier ${tier}`);
+ await handleDowngradeEvent(requestLogger, license_key, tier, prev_license_key);
break;
case "deactivate":
@@ -138,33 +140,33 @@ export async function handleAppSumoWebhook(
// For upgrade/downgrade, license_status is already "deactivated" - we skip these
const isUpgradeOrDowngradeDeactivation =
extra?.reason === "Upgraded by customer" || extra?.reason === "Downgraded by customer";
- logger.info(
+ requestLogger.info(
`[AppSumo] Deactivate event for ${license_key}, reason: ${extra?.reason}, skipping: ${isUpgradeOrDowngradeDeactivation}`
);
if (!isUpgradeOrDowngradeDeactivation) {
- await handleDeactivateEvent(license_key);
+ await handleDeactivateEvent(requestLogger, license_key);
}
break;
case "migrate":
// Add-on migration when parent license is upgraded/downgraded
// Note: parent_license_key is updated to point to new parent license
- logger.info(`[AppSumo] Handling migrate event for ${license_key}, parent: ${parent_license_key}`);
- await handleMigrateEvent(license_key, tier, parent_license_key);
+ requestLogger.info(`[AppSumo] Handling migrate event for ${license_key}, parent: ${parent_license_key}`);
+ await handleMigrateEvent(requestLogger, license_key, tier, parent_license_key);
break;
default:
- console.warn(`[AppSumo] Unknown AppSumo webhook event: ${event}`);
+ requestLogger.warn({ event }, "[AppSumo] Unknown AppSumo webhook event");
}
// Return success response as required by AppSumo
- logger.info(`[AppSumo] Successfully processed ${event} event for ${license_key}`);
+ requestLogger.info(`[AppSumo] Successfully processed ${event} event for ${license_key}`);
return reply.status(200).send({
event: event,
success: true,
});
} catch (error) {
- console.error("[AppSumo] Error processing AppSumo webhook:", error);
+ requestLogger.error({ err: error }, "[AppSumo] Error processing AppSumo webhook");
// Still return 200 to acknowledge receipt, but log the error
return reply.status(200).send({
@@ -178,9 +180,14 @@ export async function handleAppSumoWebhook(
/**
* Handle purchase event - create placeholder license record
*/
-async function handlePurchaseEvent(licenseKey: string, tier: any, parentLicenseKey?: string) {
+async function handlePurchaseEvent(
+ requestLogger: FastifyBaseLogger,
+ licenseKey: string,
+ tier: any,
+ parentLicenseKey?: string
+) {
const tierValue = tier?.toString() || "1";
- logger.info(
+ requestLogger.info(
`[AppSumo] handlePurchaseEvent - license: ${licenseKey}, tier: ${tierValue}, parent: ${parentLicenseKey}`
);
@@ -189,7 +196,7 @@ async function handlePurchaseEvent(licenseKey: string, tier: any, parentLicenseK
if (Array.isArray(existing) && existing.length === 0) {
// Create placeholder - will be linked to org when user activates
- logger.info(`[AppSumo] Creating new pending license ${licenseKey}`);
+ requestLogger.info(`[AppSumo] Creating new pending license ${licenseKey}`);
await db.execute(sql`
INSERT INTO appsumo.licenses (
organization_id,
@@ -210,18 +217,18 @@ async function handlePurchaseEvent(licenseKey: string, tier: any, parentLicenseK
)
ON CONFLICT (license_key) DO NOTHING
`);
- logger.info(`[AppSumo] Successfully created pending license ${licenseKey}`);
+ requestLogger.info(`[AppSumo] Successfully created pending license ${licenseKey}`);
} else {
- logger.info(`[AppSumo] License ${licenseKey} already exists, skipping`);
+ requestLogger.info(`[AppSumo] License ${licenseKey} already exists, skipping`);
}
}
/**
* Handle activate event - update license status
*/
-async function handleActivateEvent(licenseKey: string, tier: any) {
+async function handleActivateEvent(requestLogger: FastifyBaseLogger, licenseKey: string, tier: any) {
const tierValue = tier?.toString() || "1";
- logger.info(`[AppSumo] handleActivateEvent - license: ${licenseKey}, tier: ${tierValue}`);
+ requestLogger.info(`[AppSumo] handleActivateEvent - license: ${licenseKey}, tier: ${tierValue}`);
await db.execute(sql`
UPDATE appsumo.licenses
@@ -232,34 +239,39 @@ async function handleActivateEvent(licenseKey: string, tier: any) {
updated_at = NOW()
WHERE license_key = ${licenseKey}
`);
- logger.info(`[AppSumo] Successfully activated license ${licenseKey}`);
+ requestLogger.info(`[AppSumo] Successfully activated license ${licenseKey}`);
}
/**
* Handle upgrade event - create new license and transfer organization
*/
-async function handleUpgradeEvent(licenseKey: string, tier: any, prevLicenseKey?: string) {
+async function handleUpgradeEvent(
+ requestLogger: FastifyBaseLogger,
+ licenseKey: string,
+ tier: any,
+ prevLicenseKey?: string
+) {
const tierValue = tier?.toString() || "1";
- logger.info(
+ requestLogger.info(
`[AppSumo] handleUpgradeEvent - new license: ${licenseKey}, prev license: ${prevLicenseKey}, tier: ${tierValue}`
);
if (!prevLicenseKey) {
- console.warn("[AppSumo] No prev_license_key provided for upgrade event");
+ requestLogger.warn("[AppSumo] No prev_license_key provided for upgrade event");
return;
}
// Get the old license to find the organization
- logger.info(`[AppSumo] Querying old license: ${prevLicenseKey}`);
+ requestLogger.info(`[AppSumo] Querying old license: ${prevLicenseKey}`);
let oldLicenseResult = await db.execute(
sql`SELECT organization_id FROM appsumo.licenses WHERE license_key = ${prevLicenseKey} LIMIT 1`
);
- logger.info({ oldLicenseResult }, "[AppSumo] Old license query result");
+ requestLogger.info({ oldLicenseResult }, "[AppSumo] Old license query result");
// If previous license not found, try to find ANY license with an organization (fallback for missed webhooks)
if (!Array.isArray(oldLicenseResult) || oldLicenseResult.length === 0) {
- console.warn(
+ requestLogger.warn(
`[AppSumo] Old license not found: ${prevLicenseKey}, searching for any license with organization as fallback`
);
oldLicenseResult = await db.execute(
@@ -267,20 +279,20 @@ async function handleUpgradeEvent(licenseKey: string, tier: any, prevLicenseKey?
);
if (!Array.isArray(oldLicenseResult) || oldLicenseResult.length === 0) {
- console.error(`[AppSumo] No licenses with organization found, cannot process upgrade`);
+ requestLogger.error("[AppSumo] No licenses with organization found, cannot process upgrade");
return;
}
- logger.info({ oldLicenseResult }, "[AppSumo] Found fallback license");
+ requestLogger.info({ oldLicenseResult }, "[AppSumo] Found fallback license");
}
const oldLicense = oldLicenseResult[0] as any;
const organizationId = oldLicense.organization_id;
- logger.info(`[AppSumo] Found old license with organization_id: ${organizationId}`);
+ requestLogger.info(`[AppSumo] Found old license with organization_id: ${organizationId}`);
// Create new license with the organization transferred
if (organizationId) {
// Organization exists - create active license
- logger.info(`[AppSumo] Organization exists - creating active license for ${licenseKey}`);
+ requestLogger.info(`[AppSumo] Organization exists - creating active license for ${licenseKey}`);
try {
await db.execute(sql`
INSERT INTO appsumo.licenses (
@@ -307,14 +319,14 @@ async function handleUpgradeEvent(licenseKey: string, tier: any, prevLicenseKey?
activated_at = NOW(),
updated_at = NOW()
`);
- logger.info(`[AppSumo] Successfully created/updated active license ${licenseKey}`);
+ requestLogger.info(`[AppSumo] Successfully created/updated active license ${licenseKey}`);
} catch (error) {
- console.error(`[AppSumo] Error creating active license:`, error);
+ requestLogger.error({ err: error }, "[AppSumo] Error creating active license");
throw error;
}
} else {
// No organization yet - create pending license
- logger.info(`[AppSumo] No organization - creating pending license for ${licenseKey}`);
+ requestLogger.info(`[AppSumo] No organization - creating pending license for ${licenseKey}`);
try {
await db.execute(sql`
INSERT INTO appsumo.licenses (
@@ -337,15 +349,15 @@ async function handleUpgradeEvent(licenseKey: string, tier: any, prevLicenseKey?
status = 'pending',
updated_at = NOW()
`);
- logger.info(`[AppSumo] Successfully created/updated pending license ${licenseKey}`);
+ requestLogger.info(`[AppSumo] Successfully created/updated pending license ${licenseKey}`);
} catch (error) {
- console.error(`[AppSumo] Error creating pending license:`, error);
+ requestLogger.error({ err: error }, "[AppSumo] Error creating pending license");
throw error;
}
}
// Deactivate the old license
- logger.info(`[AppSumo] Deactivating old license ${prevLicenseKey}`);
+ requestLogger.info(`[AppSumo] Deactivating old license ${prevLicenseKey}`);
try {
await db.execute(sql`
UPDATE appsumo.licenses
@@ -355,9 +367,9 @@ async function handleUpgradeEvent(licenseKey: string, tier: any, prevLicenseKey?
updated_at = NOW()
WHERE license_key = ${prevLicenseKey}
`);
- logger.info(`[AppSumo] Successfully deactivated old license ${prevLicenseKey}`);
+ requestLogger.info(`[AppSumo] Successfully deactivated old license ${prevLicenseKey}`);
} catch (error) {
- console.error(`[AppSumo] Error deactivating old license:`, error);
+ requestLogger.error({ err: error }, "[AppSumo] Error deactivating old license");
throw error;
}
}
@@ -365,28 +377,33 @@ async function handleUpgradeEvent(licenseKey: string, tier: any, prevLicenseKey?
/**
* Handle downgrade event - create new license and transfer organization
*/
-async function handleDowngradeEvent(licenseKey: string, tier: any, prevLicenseKey?: string) {
+async function handleDowngradeEvent(
+ requestLogger: FastifyBaseLogger,
+ licenseKey: string,
+ tier: any,
+ prevLicenseKey?: string
+) {
const tierValue = tier?.toString() || "1";
- logger.info(
+ requestLogger.info(
`[AppSumo] handleDowngradeEvent - new license: ${licenseKey}, prev license: ${prevLicenseKey}, tier: ${tierValue}`
);
if (!prevLicenseKey) {
- console.warn("[AppSumo] No prev_license_key provided for downgrade event");
+ requestLogger.warn("[AppSumo] No prev_license_key provided for downgrade event");
return;
}
// Get the old license to find the organization
- logger.info(`[AppSumo] Querying old license: ${prevLicenseKey}`);
+ requestLogger.info(`[AppSumo] Querying old license: ${prevLicenseKey}`);
let oldLicenseResult = await db.execute(
sql`SELECT organization_id FROM appsumo.licenses WHERE license_key = ${prevLicenseKey} LIMIT 1`
);
- logger.info({ oldLicenseResult }, "[AppSumo] Old license query result");
+ requestLogger.info({ oldLicenseResult }, "[AppSumo] Old license query result");
// If previous license not found, try to find ANY license with an organization (fallback for missed webhooks)
if (!Array.isArray(oldLicenseResult) || oldLicenseResult.length === 0) {
- console.warn(
+ requestLogger.warn(
`[AppSumo] Old license not found: ${prevLicenseKey}, searching for any license with organization as fallback`
);
oldLicenseResult = await db.execute(
@@ -394,20 +411,20 @@ async function handleDowngradeEvent(licenseKey: string, tier: any, prevLicenseKe
);
if (!Array.isArray(oldLicenseResult) || oldLicenseResult.length === 0) {
- console.error(`[AppSumo] No licenses with organization found, cannot process downgrade`);
+ requestLogger.error("[AppSumo] No licenses with organization found, cannot process downgrade");
return;
}
- logger.info({ oldLicenseResult }, "[AppSumo] Found fallback license");
+ requestLogger.info({ oldLicenseResult }, "[AppSumo] Found fallback license");
}
const oldLicense = oldLicenseResult[0] as any;
const organizationId = oldLicense.organization_id;
- logger.info(`[AppSumo] Found old license with organization_id: ${organizationId}`);
+ requestLogger.info(`[AppSumo] Found old license with organization_id: ${organizationId}`);
// Create new license with the organization transferred
if (organizationId) {
// Organization exists - create active license
- logger.info(`[AppSumo] Organization exists - creating active license for ${licenseKey}`);
+ requestLogger.info(`[AppSumo] Organization exists - creating active license for ${licenseKey}`);
try {
await db.execute(sql`
INSERT INTO appsumo.licenses (
@@ -434,14 +451,14 @@ async function handleDowngradeEvent(licenseKey: string, tier: any, prevLicenseKe
activated_at = NOW(),
updated_at = NOW()
`);
- logger.info(`[AppSumo] Successfully created/updated active license ${licenseKey}`);
+ requestLogger.info(`[AppSumo] Successfully created/updated active license ${licenseKey}`);
} catch (error) {
- console.error(`[AppSumo] Error creating active license:`, error);
+ requestLogger.error({ err: error }, "[AppSumo] Error creating active license");
throw error;
}
} else {
// No organization yet - create pending license
- logger.info(`[AppSumo] No organization - creating pending license for ${licenseKey}`);
+ requestLogger.info(`[AppSumo] No organization - creating pending license for ${licenseKey}`);
try {
await db.execute(sql`
INSERT INTO appsumo.licenses (
@@ -464,15 +481,15 @@ async function handleDowngradeEvent(licenseKey: string, tier: any, prevLicenseKe
status = 'pending',
updated_at = NOW()
`);
- logger.info(`[AppSumo] Successfully created/updated pending license ${licenseKey}`);
+ requestLogger.info(`[AppSumo] Successfully created/updated pending license ${licenseKey}`);
} catch (error) {
- console.error(`[AppSumo] Error creating pending license:`, error);
+ requestLogger.error({ err: error }, "[AppSumo] Error creating pending license");
throw error;
}
}
// Deactivate the old license
- logger.info(`[AppSumo] Deactivating old license ${prevLicenseKey}`);
+ requestLogger.info(`[AppSumo] Deactivating old license ${prevLicenseKey}`);
try {
await db.execute(sql`
UPDATE appsumo.licenses
@@ -482,9 +499,9 @@ async function handleDowngradeEvent(licenseKey: string, tier: any, prevLicenseKe
updated_at = NOW()
WHERE license_key = ${prevLicenseKey}
`);
- logger.info(`[AppSumo] Successfully deactivated old license ${prevLicenseKey}`);
+ requestLogger.info(`[AppSumo] Successfully deactivated old license ${prevLicenseKey}`);
} catch (error) {
- console.error(`[AppSumo] Error deactivating old license:`, error);
+ requestLogger.error({ err: error }, "[AppSumo] Error deactivating old license");
throw error;
}
}
@@ -492,8 +509,8 @@ async function handleDowngradeEvent(licenseKey: string, tier: any, prevLicenseKe
/**
* Handle deactivate event - mark license as inactive
*/
-async function handleDeactivateEvent(licenseKey: string) {
- logger.info(`[AppSumo] handleDeactivateEvent - license: ${licenseKey}`);
+async function handleDeactivateEvent(requestLogger: FastifyBaseLogger, licenseKey: string) {
+ requestLogger.info(`[AppSumo] handleDeactivateEvent - license: ${licenseKey}`);
await db.execute(sql`
UPDATE appsumo.licenses
SET
@@ -502,15 +519,22 @@ async function handleDeactivateEvent(licenseKey: string) {
updated_at = NOW()
WHERE license_key = ${licenseKey}
`);
- logger.info(`[AppSumo] Successfully deactivated license ${licenseKey}`);
+ requestLogger.info(`[AppSumo] Successfully deactivated license ${licenseKey}`);
}
/**
* Handle migrate event - update parent license for add-ons
*/
-async function handleMigrateEvent(licenseKey: string, tier: any, parentLicenseKey?: string) {
+async function handleMigrateEvent(
+ requestLogger: FastifyBaseLogger,
+ licenseKey: string,
+ tier: any,
+ parentLicenseKey?: string
+) {
const tierValue = tier?.toString() || "1";
- logger.info(`[AppSumo] handleMigrateEvent - license: ${licenseKey}, tier: ${tierValue}, parent: ${parentLicenseKey}`);
+ requestLogger.info(
+ `[AppSumo] handleMigrateEvent - license: ${licenseKey}, tier: ${tierValue}, parent: ${parentLicenseKey}`
+ );
await db.execute(sql`
UPDATE appsumo.licenses
@@ -520,5 +544,5 @@ async function handleMigrateEvent(licenseKey: string, tier: any, parentLicenseKe
updated_at = NOW()
WHERE license_key = ${licenseKey}
`);
- logger.info(`[AppSumo] Successfully migrated license ${licenseKey}`);
+ requestLogger.info(`[AppSumo] Successfully migrated license ${licenseKey}`);
}
diff --git a/server/src/api/gsc/callback.ts b/server/src/api/gsc/callback.ts
index 58a4ebdf0..5581d2c07 100644
--- a/server/src/api/gsc/callback.ts
+++ b/server/src/api/gsc/callback.ts
@@ -5,7 +5,6 @@ import { eq } from "drizzle-orm";
import { getGSCProperties, verifyGSCState } from "./utils.js";
import { getSessionFromReq, getUserHasAdminAccessToSite } from "../../lib/auth-utils.js";
import { db } from "../../db/postgres/postgres.js";
-import { logger } from "../../lib/logger/logger.js";
interface TokenResponse {
access_token: string;
@@ -24,7 +23,7 @@ export async function gscCallback(req: FastifyRequest<GSCCallbackRequest>, res:
const { code, state, error } = req.query;
if (error) {
- logger.info(`OAuth cancelled or failed: ${error}`);
+ req.log.info({ oauthError: error }, "GSC OAuth was cancelled or failed");
return res.redirect(`${process.env.BASE_URL}`);
}
@@ -83,14 +82,17 @@ export async function gscCallback(req: FastifyRequest<GSCCallbackRequest>, res:
});
if (!tokenResponse.ok) {
- logger.error(`Token exchange failed: ${await tokenResponse.text()}`);
+ req.log.error(
+ { responseBody: await tokenResponse.text(), statusCode: tokenResponse.status },
+ "GSC token exchange failed"
+ );
return res.redirect(`${process.env.BASE_URL}/error?message=Token exchange failed`);
}
const tokens: TokenResponse = await tokenResponse.json();
// Get available GSC properties
- const properties = await getGSCProperties(tokens.access_token);
+ const properties = await getGSCProperties(tokens.access_token, req.log);
if (properties.length === 0) {
return res.redirect(`${process.env.CLIENT_URL}/error?message=No GSC properties found`);
@@ -130,7 +132,7 @@ export async function gscCallback(req: FastifyRequest<GSCCallbackRequest>, res:
const propertiesParam = encodeURIComponent(JSON.stringify(properties));
return res.redirect(`${process.env.BASE_URL}/${siteId}/gsc/select-property?properties=${propertiesParam}`);
} catch (error) {
- logger.error(error, "Error handling GSC callback");
+ req.log.error(error, "Error handling GSC callback");
return res.redirect(`${process.env.BASE_URL}/error?message=Callback failed`);
}
}
diff --git a/server/src/api/gsc/connect.ts b/server/src/api/gsc/connect.ts
index 3b7f7a613..2975dde6a 100644
--- a/server/src/api/gsc/connect.ts
+++ b/server/src/api/gsc/connect.ts
@@ -1,7 +1,6 @@
import { FastifyReply, FastifyRequest } from "fastify";
import { ConnectGSCRequest } from "./types.js";
import { getSessionFromReq, getUserHasAdminAccessToSite } from "../../lib/auth-utils.js";
-import { logger } from "../../lib/logger/logger.js";
import { signGSCState } from "./utils.js";
/**
@@ -54,7 +53,7 @@ export async function connectGSC(req: FastifyRequest<ConnectGSCRequest>, res: Fa
return res.send({ authUrl: authUrl.toString() });
} catch (error) {
- logger.error(error, "Error initiating GSC OAuth");
+ req.log.error(error, "Error initiating GSC OAuth");
return res.status(500).send({ error: "Failed to initiate OAuth" });
}
}
diff --git a/server/src/api/gsc/disconnect.ts b/server/src/api/gsc/disconnect.ts
index 7ad800675..1eace3538 100644
--- a/server/src/api/gsc/disconnect.ts
+++ b/server/src/api/gsc/disconnect.ts
@@ -4,7 +4,6 @@ import { gscConnections } from "../../db/postgres/schema.js";
import { eq } from "drizzle-orm";
import { getUserHasAdminAccessToSite } from "../../lib/auth-utils.js";
import { db } from "../../db/postgres/postgres.js";
-import { logger } from "../../lib/logger/logger.js";
/**
* Disconnects a site from Google Search Console
@@ -31,7 +30,7 @@ export async function disconnectGSC(req: FastifyRequest<DisconnectGSCRequest>, r
return res.send({ success: true });
} catch (error) {
- logger.error(error, "Error disconnecting GSC");
+ req.log.error(error, "Error disconnecting GSC");
return res.status(500).send({ error: "Failed to disconnect GSC" });
}
}
diff --git a/server/src/api/gsc/getData.ts b/server/src/api/gsc/getData.ts
index e9b3a89a2..d505c2376 100644
--- a/server/src/api/gsc/getData.ts
+++ b/server/src/api/gsc/getData.ts
@@ -6,7 +6,6 @@ import { refreshGSCToken } from "./utils.js";
import { getUserHasAccessToSite } from "../../lib/auth-utils.js";
import { db } from "../../db/postgres/postgres.js";
import countries from "i18n-iso-countries";
-import { logger } from "../../lib/logger/logger.js";
/**
* Fetches data from Google Search Console API with support for multiple dimensions
@@ -37,7 +36,7 @@ export async function getGSCData(req: FastifyRequest<GetGSCDataRequest>, res: Fa
}
// Refresh token if needed
- const accessToken = await refreshGSCToken(numericSiteId);
+ const accessToken = await refreshGSCToken(numericSiteId, req.log);
if (!accessToken) {
return res.status(500).send({ error: "Failed to refresh access token" });
}
@@ -62,7 +61,7 @@ export async function getGSCData(req: FastifyRequest<GetGSCDataRequest>, res: Fa
if (!gscResponse.ok) {
const errorText = await gscResponse.text();
- logger.error(`GSC API error: ${errorText}`);
+ req.log.error({ responseBody: errorText, statusCode: gscResponse.status }, "GSC request failed");
return res.status(gscResponse.status).send({ error: "Failed to fetch GSC data", details: errorText });
}
@@ -88,7 +87,7 @@ export async function getGSCData(req: FastifyRequest<GetGSCDataRequest>, res: Fa
return res.send({ data: results });
} catch (error) {
- logger.error(error, "Error fetching GSC data");
+ req.log.error(error, "Error fetching GSC data");
return res.status(500).send({ error: "Failed to fetch GSC data" });
}
}
diff --git a/server/src/api/gsc/selectProperty.ts b/server/src/api/gsc/selectProperty.ts
index acb582972..31a7edec0 100644
--- a/server/src/api/gsc/selectProperty.ts
+++ b/server/src/api/gsc/selectProperty.ts
@@ -3,7 +3,6 @@ import { gscConnections } from "../../db/postgres/schema.js";
import { eq } from "drizzle-orm";
import { getUserHasAdminAccessToSite } from "../../lib/auth-utils.js";
import { db } from "../../db/postgres/postgres.js";
-import { logger } from "../../lib/logger/logger.js";
import { getGSCProperties, refreshGSCToken } from "./utils.js";
interface SelectPropertyRequest {
@@ -41,12 +40,12 @@ export async function selectGSCProperty(req: FastifyRequest<SelectPropertyReques
// The property must be one the connected Google account actually owns.
// Accepting an arbitrary string would silently break every later data fetch
// (Google returns 403 for unowned properties) until the site is reconnected.
- const accessToken = await refreshGSCToken(numericSiteId);
+ const accessToken = await refreshGSCToken(numericSiteId, req.log);
if (!accessToken) {
return res.status(404).send({ error: "GSC connection not found" });
}
- const availableProperties = await getGSCProperties(accessToken);
+ const availableProperties = await getGSCProperties(accessToken, req.log);
if (!availableProperties.includes(propertyUrl)) {
return res.status(400).send({ error: "Selected property is not available for the connected account" });
}
@@ -67,7 +66,7 @@ export async function selectGSCProperty(req: FastifyRequest<SelectPropertyReques
return res.send({ success: true, property: propertyUrl });
} catch (error) {
- logger.error(error, "Error selecting GSC property");
+ req.log.error(error, "Error selecting GSC property");
return res.status(500).send({ error: "Failed to select property" });
}
}
diff --git a/server/src/api/gsc/status.ts b/server/src/api/gsc/status.ts
index b913e6bbb..d126b6000 100644
--- a/server/src/api/gsc/status.ts
+++ b/server/src/api/gsc/status.ts
@@ -2,7 +2,6 @@ import { eq } from "drizzle-orm";
import { FastifyReply, FastifyRequest } from "fastify";
import { db } from "../../db/postgres/postgres.js";
import { gscConnections } from "../../db/postgres/schema.js";
-import { logger } from "../../lib/logger/logger.js";
import { GetGSCStatusRequest } from "./types.js";
/**
@@ -31,7 +30,7 @@ export async function getGSCStatus(req: FastifyRequest<GetGSCStatusRequest>, res
gscPropertyUrl: connection.gscPropertyUrl,
});
} catch (error) {
- logger.error(error, "Error checking GSC status");
+ req.log.error(error, "Error checking GSC status");
return res.status(500).send({ error: "Failed to check GSC status" });
}
}
diff --git a/server/src/api/gsc/utils.ts b/server/src/api/gsc/utils.ts
index 90497f3d5..79588195a 100644
--- a/server/src/api/gsc/utils.ts
+++ b/server/src/api/gsc/utils.ts
@@ -1,8 +1,8 @@
import crypto from "crypto";
+import type { FastifyBaseLogger } from "fastify";
import { db } from "../../db/postgres/postgres.js";
import { gscConnections } from "../../db/postgres/schema.js";
import { eq } from "drizzle-orm";
-import { logger } from "../../lib/logger/logger.js";
import { SECRET } from "../../lib/const.js";
// How long a signed OAuth state remains valid (15 minutes).
@@ -76,7 +76,7 @@ interface GSCTokens {
/**
* Refresh the GSC OAuth token if it's expired
*/
-export async function refreshGSCToken(siteId: number): Promise<string | null> {
+export async function refreshGSCToken(siteId: number, requestLogger: FastifyBaseLogger): Promise<string | null> {
try {
const [connection] = await db.select().from(gscConnections).where(eq(gscConnections.siteId, siteId));
@@ -109,7 +109,10 @@ export async function refreshGSCToken(siteId: number): Promise<string | null> {
});
if (!tokenResponse.ok) {
- logger.error(`Failed to refresh GSC token: ${await tokenResponse.text()}`);
+ requestLogger.error(
+ { responseBody: await tokenResponse.text(), statusCode: tokenResponse.status },
+ "Failed to refresh GSC token"
+ );
return null;
}
@@ -133,7 +136,7 @@ export async function refreshGSCToken(siteId: number): Promise<string | null> {
return tokens.access_token;
} catch (error) {
- logger.error(error, "Error refreshing GSC token");
+ requestLogger.error(error, "Error refreshing GSC token");
return null;
}
}
@@ -141,7 +144,7 @@ export async function refreshGSCToken(siteId: number): Promise<string | null> {
/**
* Get available GSC properties for a given access token
*/
-export async function getGSCProperties(accessToken: string): Promise<string[]> {
+export async function getGSCProperties(accessToken: string, requestLogger: FastifyBaseLogger): Promise<string[]> {
try {
const response = await fetch("https://www.googleapis.com/webmasters/v3/sites", {
headers: {
@@ -150,14 +153,17 @@ export async function getGSCProperties(accessToken: string): Promise<string[]> {
});
if (!response.ok) {
- logger.error(`Failed to fetch GSC properties: ${await response.text()}`);
+ requestLogger.error(
+ { responseBody: await response.text(), statusCode: response.status },
+ "Failed to fetch GSC properties"
+ );
return [];
}
const data = await response.json();
return data.siteEntry?.map((site: { siteUrl: string }) => site.siteUrl) || [];
} catch (error) {
- logger.error(error, "Error fetching GSC properties");
+ requestLogger.error(error, "Error fetching GSC properties");
return [];
}
}
diff --git a/server/src/api/memberAccess/updateMemberSiteAccess.ts b/server/src/api/memberAccess/updateMemberSiteAccess.ts
index 35c396be3..2bd3231b1 100644
--- a/server/src/api/memberAccess/updateMemberSiteAccess.ts
+++ b/server/src/api/memberAccess/updateMemberSiteAccess.ts
@@ -70,10 +70,7 @@ export async function updateMemberSiteAccess(
}
// Update member's hasRestrictedSiteAccess flag
- await db
- .update(member)
- .set({ hasRestrictedSiteAccess })
- .where(eq(member.id, memberId));
+ await db.update(member).set({ hasRestrictedSiteAccess }).where(eq(member.id, memberId));
// Delete existing site access entries
await db.delete(memberSiteAccess).where(eq(memberSiteAccess.memberId, memberId));
@@ -113,7 +110,7 @@ export async function updateMemberSiteAccess(
})),
});
} catch (error) {
- console.error("Error updating member site access:", error);
+ request.log.error({ err: error }, "Error updating member site access");
return reply.status(500).send({ error: "Failed to update member site access" });
}
}
diff --git a/server/src/api/sessionReplay/deleteSessionReplay.ts b/server/src/api/sessionReplay/deleteSessionReplay.ts
index e6fbec381..cde37b3e8 100644
--- a/server/src/api/sessionReplay/deleteSessionReplay.ts
+++ b/server/src/api/sessionReplay/deleteSessionReplay.ts
@@ -30,7 +30,7 @@ export async function deleteSessionReplay(
return reply.status(200).send({ success: true });
} catch (error) {
- console.error("Error deleting session replay:", error);
+ request.log.error({ err: error }, "Error deleting session replay");
return reply.status(500).send({ error: "Failed to delete session replay" });
}
}
diff --git a/server/src/api/sessionReplay/getSessionReplayEvents.ts b/server/src/api/sessionReplay/getSessionReplayEvents.ts
index 2c8fef438..8274eac39 100644
--- a/server/src/api/sessionReplay/getSessionReplayEvents.ts
+++ b/server/src/api/sessionReplay/getSessionReplayEvents.ts
@@ -30,7 +30,7 @@ export async function getSessionReplayEvents(
metadata: enrichedMetadata,
});
} catch (error) {
- console.error("Error fetching session replay events:", error);
+ request.log.error({ err: error }, "Error fetching session replay events");
if (error instanceof Error && error.message === "Session replay not found") {
return reply.status(404).send({ error: "Session replay not found" });
}
diff --git a/server/src/api/sessionReplay/getSessionReplays.ts b/server/src/api/sessionReplay/getSessionReplays.ts
index 2a2f575d8..3fe1abc8f 100644
--- a/server/src/api/sessionReplay/getSessionReplays.ts
+++ b/server/src/api/sessionReplay/getSessionReplays.ts
@@ -41,7 +41,7 @@ export async function getSessionReplays(
return reply.send({ data: replaysWithTraits });
} catch (error) {
- console.error("Error fetching session replays:", error);
+ request.log.error({ err: error }, "Error fetching session replays");
return reply.status(500).send({ error: "Internal server error" });
}
}
diff --git a/server/src/api/sessionReplay/recordSessionReplay.test.ts b/server/src/api/sessionReplay/recordSessionReplay.test.ts
index 5b4d45385..adb1de229 100644
--- a/server/src/api/sessionReplay/recordSessionReplay.test.ts
+++ b/server/src/api/sessionReplay/recordSessionReplay.test.ts
@@ -36,13 +36,6 @@ vi.mock("../../services/replay/sessionReplayIngestService.js", () => ({
})),
}));
-vi.mock("../../lib/logger/logger.js", () => ({
- logger: {
- info: mocks.loggerInfo,
- error: mocks.loggerError,
- },
-}));
-
type ReplyStub = FastifyReply & {
statusCodeValue: number;
sentPayload: unknown;
@@ -93,6 +86,10 @@ function createRequest(overrides: RequestOverrides = {}): ReplayRequest {
...overrides.headers,
},
ip: overrides.ip ?? "203.0.113.10",
+ log: {
+ error: mocks.loggerError,
+ info: mocks.loggerInfo,
+ },
} as unknown as ReplayRequest;
}
diff --git a/server/src/api/sessionReplay/recordSessionReplay.ts b/server/src/api/sessionReplay/recordSessionReplay.ts
index bcd8da560..05971f083 100644
--- a/server/src/api/sessionReplay/recordSessionReplay.ts
+++ b/server/src/api/sessionReplay/recordSessionReplay.ts
@@ -5,7 +5,6 @@ import { SessionReplayIngestService } from "../../services/replay/sessionReplayI
import { usageService } from "../../services/usageService.js";
import { RecordSessionReplayRequest } from "../../types/sessionReplay.js";
import { resolveClientIp } from "../../services/tracker/resolveClientIp.js";
-import { logger } from "../../lib/logger/logger.js";
import { decideSiteExclusion } from "../../services/sites/siteExclusionDecision.js";
const recordSessionReplaySchema = z.object({
@@ -62,7 +61,7 @@ export async function recordSessionReplay(
const { siteId, sessionReplay } = siteConfiguration ?? {};
if (!sessionReplay) {
- logger.info(`[SessionReplay] Skipping event for site ${siteId} - session replay not enabled`);
+ request.log.info({ siteId }, "Skipping session replay event because replay is not enabled");
return reply.status(200).send({ success: true, message: "Session replay not enabled" });
}
@@ -76,14 +75,14 @@ export async function recordSessionReplay(
// Check if the site has exceeded its monthly limit
if (usageService.isSiteOverLimit(Number(siteId))) {
- logger.info(`[SessionReplay] Skipping event for site ${siteId} - over monthly limit`);
+ request.log.info({ siteId }, "Skipping session replay event because the Site is over its monthly limit");
return reply.status(200).send("Site over monthly limit, event not tracked");
}
// Check if the site can record replays: the plan may not include them (e.g. enabled
// before a downgrade from Pro) or the monthly replay quota may be exhausted
if (usageService.isSiteWithoutReplay(Number(siteId))) {
- logger.info(`[SessionReplay] Skipping event for site ${siteId} - replay not available for plan or quota`);
+ request.log.info({ siteId }, "Skipping session replay event because replay is unavailable for plan or quota");
return reply.status(200).send({ success: true, message: "Session replay not available for plan or quota" });
}
@@ -101,7 +100,10 @@ export async function recordSessionReplay(
});
if (exclusionDecision.excluded) {
- logger.info(`[SessionReplay] ${exclusionDecision.label} excluded from tracking for site ${siteId}`);
+ request.log.info(
+ { siteId, exclusionReason: exclusionDecision.reason },
+ "Skipping session replay event because a Site Exclusion Decision matched"
+ );
return reply.status(200).send({
success: true,
message: `Session replay not recorded - ${exclusionDecision.label} excluded`,
@@ -124,7 +126,7 @@ export async function recordSessionReplay(
if (error instanceof z.ZodError) {
return reply.status(400).send({ error: error.errors });
}
- logger.error(error as Error, "Error recording session replay");
+ request.log.error(error as Error, "Error recording session replay");
return reply.status(500).send({ error });
}
}
diff --git a/server/src/api/sites/addSite.ts b/server/src/api/sites/addSite.ts
index 483387ec5..64f46b876 100644
--- a/server/src/api/sites/addSite.ts
+++ b/server/src/api/sites/addSite.ts
@@ -30,7 +30,7 @@ export async function addSite(
});
}
- console.error("Error adding site:", error);
+ request.log.error({ err: error }, "Error adding site");
return reply.status(500).send({
error: "Internal server error",
});
diff --git a/server/src/api/sites/batchImportEvents.ts b/server/src/api/sites/batchImportEvents.ts
index b6a2eec4c..31f7bee75 100644
--- a/server/src/api/sites/batchImportEvents.ts
+++ b/server/src/api/sites/batchImportEvents.ts
@@ -120,7 +120,7 @@ export async function batchImportEvents(request: FastifyRequest<BatchImportReque
return reply.send();
} catch (insertError) {
const errorMessage = insertError instanceof Error ? insertError.message : "Unknown error";
- console.error("Failed to insert events:", errorMessage);
+ request.log.error({ err: insertError }, "Failed to insert imported events");
if (isLastBatch) {
await completeImport(importId);
@@ -132,7 +132,7 @@ export async function batchImportEvents(request: FastifyRequest<BatchImportReque
});
}
} catch (error) {
- console.error("Error importing events", error);
+ request.log.error({ err: error }, "Error importing events");
return reply.status(500).send({ error: "Internal server error" });
}
}
diff --git a/server/src/api/sites/createSiteImport.ts b/server/src/api/sites/createSiteImport.ts
index 56c26925f..4dc6f16e9 100644
--- a/server/src/api/sites/createSiteImport.ts
+++ b/server/src/api/sites/createSiteImport.ts
@@ -95,11 +95,11 @@ export async function createSiteImport(request: FastifyRequest<CreateSiteImportR
});
} catch (error) {
importQuotaManager.completeImport(organizationId);
- console.error("Error creating import:", error);
+ request.log.error({ err: error }, "Error creating import");
return reply.status(500).send({ error: "Internal server error" });
}
} catch (error) {
- console.error("Error creating import:", error);
+ request.log.error({ err: error }, "Error creating import");
return reply.status(500).send({ error: "Internal server error" });
}
}
diff --git a/server/src/api/sites/deleteSite.ts b/server/src/api/sites/deleteSite.ts
index e88b53bb3..604cd49ac 100644
--- a/server/src/api/sites/deleteSite.ts
+++ b/server/src/api/sites/deleteSite.ts
@@ -16,7 +16,7 @@ export async function deleteSite(request: FastifyRequest<{ Params: { siteId: str
return reply.status(error.statusCode).send({ success: false, error: error.message });
}
- console.error("Error deleting site:", error);
+ request.log.error({ err: error }, "Error deleting site");
return reply.status(500).send({ success: false, error: "Failed to delete site" });
}
}
diff --git a/server/src/api/sites/deleteSiteImport.ts b/server/src/api/sites/deleteSiteImport.ts
index 161c93e9b..6118509a0 100644
--- a/server/src/api/sites/deleteSiteImport.ts
+++ b/server/src/api/sites/deleteSiteImport.ts
@@ -91,7 +91,7 @@ export async function deleteSiteImport(request: FastifyRequest<DeleteImportReque
return reply.send();
} catch (error) {
- console.error("Error deleting import:", error);
+ request.log.error({ err: error }, "Error deleting import");
return reply.status(500).send({ error: "Internal server error" });
}
}
diff --git a/server/src/api/sites/getSite.ts b/server/src/api/sites/getSite.ts
index 7231c793f..6caa95524 100644
--- a/server/src/api/sites/getSite.ts
+++ b/server/src/api/sites/getSite.ts
@@ -55,7 +55,7 @@ export async function getSite(request: FastifyRequest<GetSiteParams>, reply: Fas
trackFormInteractions: site.trackFormInteractions,
});
} catch (error) {
- console.error("Error retrieving site:", error);
+ request.log.error({ err: error }, "Error retrieving site");
return reply.status(500).send({ error: "Internal server error" });
}
}
diff --git a/server/src/api/sites/getSiteExcludedCountries.ts b/server/src/api/sites/getSiteExcludedCountries.ts
index 4a42692c5..de10c6da3 100644
--- a/server/src/api/sites/getSiteExcludedCountries.ts
+++ b/server/src/api/sites/getSiteExcludedCountries.ts
@@ -45,7 +45,7 @@ export async function getSiteExcludedCountries(request: FastifyRequest, reply: F
excludedCountries,
});
} catch (error) {
- console.error("Error getting excluded countries:", error);
+ request.log.error({ err: error }, "Error getting excluded countries");
return reply.status(500).send({
success: false,
error: "Failed to get excluded countries",
diff --git a/server/src/api/sites/getSiteExcludedIPs.ts b/server/src/api/sites/getSiteExcludedIPs.ts
index 8284762fb..ef49a37ef 100644
--- a/server/src/api/sites/getSiteExcludedIPs.ts
+++ b/server/src/api/sites/getSiteExcludedIPs.ts
@@ -54,7 +54,7 @@ export async function getSiteExcludedIPs(request: FastifyRequest, reply: Fastify
excludedIPs,
});
} catch (error) {
- console.error("Error getting excluded IPs:", error);
+ request.log.error({ err: error }, "Error getting excluded IPs");
return reply.status(500).send({
success: false,
error: "Failed to get excluded IPs",
diff --git a/server/src/api/sites/getSiteExclusions.ts b/server/src/api/sites/getSiteExclusions.ts
index 9310ba9c0..abf169d6b 100644
--- a/server/src/api/sites/getSiteExclusions.ts
+++ b/server/src/api/sites/getSiteExclusions.ts
@@ -53,7 +53,7 @@ async function getExclusionColumn(
[responseKey]: value,
});
} catch (error) {
- console.error(`Error getting ${responseKey}:`, error);
+ request.log.error({ err: error }, `Error getting ${responseKey}`);
return reply.status(500).send({
success: false,
error: `Failed to get ${responseKey}`,
diff --git a/server/src/api/sites/getSiteHasData.ts b/server/src/api/sites/getSiteHasData.ts
index 8926d4d2f..075d42d6c 100644
--- a/server/src/api/sites/getSiteHasData.ts
+++ b/server/src/api/sites/getSiteHasData.ts
@@ -21,7 +21,7 @@ export async function getSiteHasData(request: FastifyRequest<{ Params: { siteId:
hasData,
};
} catch (error) {
- console.error("Error checking if site has data:", error);
+ request.log.error({ err: error }, "Error checking if site has data");
return reply.status(500).send({ error: "Internal server error" });
}
}
diff --git a/server/src/api/sites/getSiteImports.ts b/server/src/api/sites/getSiteImports.ts
index 74e6f7ba0..5c5d26fd3 100644
--- a/server/src/api/sites/getSiteImports.ts
+++ b/server/src/api/sites/getSiteImports.ts
@@ -69,7 +69,7 @@ export async function getSiteImports(request: FastifyRequest<GetSiteImportsReque
),
});
} catch (error) {
- console.error("Error fetching imports:", error);
+ request.log.error({ err: error }, "Error fetching imports");
return reply.status(500).send({ error: "Internal server error" });
}
}
diff --git a/server/src/api/sites/getSitePrivateLinkConfig.ts b/server/src/api/sites/getSitePrivateLinkConfig.ts
index 5e58a963e..8769109bf 100644
--- a/server/src/api/sites/getSitePrivateLinkConfig.ts
+++ b/server/src/api/sites/getSitePrivateLinkConfig.ts
@@ -35,7 +35,7 @@ export async function getSitePrivateLinkConfig(
},
});
} catch (error) {
- console.error("Error getting site private link configuration:", error);
+ request.log.error({ err: error }, "Error getting site private link configuration");
return reply.status(500).send({
success: false,
error: "Failed to get site private link configuration",
diff --git a/server/src/api/sites/getSiteUsage.ts b/server/src/api/sites/getSiteUsage.ts
index c46d8c9c4..5ad6dfae4 100644
--- a/server/src/api/sites/getSiteUsage.ts
+++ b/server/src/api/sites/getSiteUsage.ts
@@ -120,7 +120,7 @@ export async function getSiteUsage(request: FastifyRequest<GetSiteUsageRequest>,
return reply.send(response);
} catch (error) {
- console.error("Error fetching site usage:", error);
+ request.log.error({ err: error }, "Error fetching site usage");
return reply.status(500).send({ error: "Internal server error" });
}
}
diff --git a/server/src/api/sites/getSitesFromOrg.ts b/server/src/api/sites/getSitesFromOrg.ts
index 94c9c9521..4edd16cd7 100644
--- a/server/src/api/sites/getSitesFromOrg.ts
+++ b/server/src/api/sites/getSitesFromOrg.ts
@@ -139,7 +139,7 @@ export async function getSitesFromOrg(
},
});
} catch (err) {
- console.error("Error in getSitesFromOrg:", err);
+ req.log.error({ err: err }, "Error in getSitesFromOrg");
return res.status(500).send({ error: String(err) });
}
}
diff --git a/server/src/api/sites/getTrackingConfig.ts b/server/src/api/sites/getTrackingConfig.ts
index a8af37933..b0f1c19ef 100644
--- a/server/src/api/sites/getTrackingConfig.ts
+++ b/server/src/api/sites/getTrackingConfig.ts
@@ -34,7 +34,7 @@ export async function getTrackingConfig(request: FastifyRequest<{ Params: { site
trackFormInteractions: config.trackFormInteractions || false,
});
} catch (error) {
- console.error("Error getting tracking config:", error);
+ request.log.error({ err: error }, "Error getting tracking config");
return reply.status(500).send({ error: "Failed to get tracking configuration" });
}
}
diff --git a/server/src/api/sites/moveSite.ts b/server/src/api/sites/moveSite.ts
index a79eae456..e225279af 100644
--- a/server/src/api/sites/moveSite.ts
+++ b/server/src/api/sites/moveSite.ts
@@ -95,7 +95,7 @@ export async function moveSite(
return reply.status(200).send({ success: true, organizationId: targetOrganizationId });
} catch (error) {
- console.error("Error moving site:", error);
+ request.log.error({ err: error }, "Error moving site");
return reply.status(500).send({ error: "Failed to move site" });
}
}
diff --git a/server/src/api/sites/updateSiteConfig.ts b/server/src/api/sites/updateSiteConfig.ts
index 80f7c7c47..4c92892e3 100644
--- a/server/src/api/sites/updateSiteConfig.ts
+++ b/server/src/api/sites/updateSiteConfig.ts
@@ -78,7 +78,7 @@ export async function updateSiteConfig(
});
}
- console.error("Error updating site configuration:", error);
+ request.log.error({ err: error }, "Error updating site configuration");
return reply.status(500).send({
success: false,
error: "Failed to update site configuration",
diff --git a/server/src/api/sites/updateSitePrivateLinkConfig.ts b/server/src/api/sites/updateSitePrivateLinkConfig.ts
index 793ba1368..850b68494 100644
--- a/server/src/api/sites/updateSitePrivateLinkConfig.ts
+++ b/server/src/api/sites/updateSitePrivateLinkConfig.ts
@@ -38,7 +38,7 @@ export async function updateSitePrivateLinkConfig(request: FastifyRequest, reply
return reply.status(error.statusCode).send({ success: false, error: error.message });
}
- console.error("Error updating site private link config:", error);
+ request.log.error({ err: error }, "Error updating site private link config");
return reply.status(500).send({
success: false,
error: "Failed to update site API configuration",
diff --git a/server/src/api/stripe/createCheckoutSession.ts b/server/src/api/stripe/createCheckoutSession.ts
index 9ab519e0d..16028eb86 100644
--- a/server/src/api/stripe/createCheckoutSession.ts
+++ b/server/src/api/stripe/createCheckoutSession.ts
@@ -127,7 +127,7 @@ export async function createCheckoutSession(
// 6. Return the client secret for embedded checkout
return reply.send({ clientSecret: session.client_secret });
} catch (error: any) {
- console.error("Stripe Checkout Session Error:", error);
+ request.log.error({ err: error }, "Stripe Checkout Session Error");
return reply.status(500).send({
error: "Failed to create Stripe checkout session",
details: error.message,
diff --git a/server/src/api/stripe/createPortalSession.ts b/server/src/api/stripe/createPortalSession.ts
index f327d32aa..e6da8cbd5 100644
--- a/server/src/api/stripe/createPortalSession.ts
+++ b/server/src/api/stripe/createPortalSession.ts
@@ -140,7 +140,7 @@ export async function createPortalSession(request: FastifyRequest<{ Body: Portal
// 4. Return the Billing Portal Session URL
return reply.send({ portalUrl: portalSession.url });
} catch (error: any) {
- console.error("Stripe Portal Session Error:", error);
+ request.log.error({ err: error }, "Stripe Portal Session Error");
return reply.status(500).send({
error: "Failed to create Stripe portal session",
details: error.message,
diff --git a/server/src/api/stripe/getInvoices.test.ts b/server/src/api/stripe/getInvoices.test.ts
index c55bfecf2..7bdcbcc6e 100644
--- a/server/src/api/stripe/getInvoices.test.ts
+++ b/server/src/api/stripe/getInvoices.test.ts
@@ -43,7 +43,11 @@ function replyStub() {
}
function requestStub(userId: string | undefined, query: Record<string, unknown>) {
- return { user: userId ? { id: userId } : undefined, query } as any;
+ return {
+ user: userId ? { id: userId } : undefined,
+ query,
+ log: { error: vi.fn() },
+ } as any;
}
const fakeInvoice = {
diff --git a/server/src/api/stripe/getInvoices.ts b/server/src/api/stripe/getInvoices.ts
index cf2a34f9f..f517460c7 100644
--- a/server/src/api/stripe/getInvoices.ts
+++ b/server/src/api/stripe/getInvoices.ts
@@ -72,7 +72,7 @@ export async function getInvoices(
return reply.send(formatted);
} catch (error: any) {
- console.error("Get Invoices Error:", error);
+ request.log.error({ err: error }, "Get Invoices Error");
return reply.status(500).send({
error: "Failed to fetch invoices",
});
diff --git a/server/src/api/stripe/getSubscription.ts b/server/src/api/stripe/getSubscription.ts
index b62a72470..74624a8f8 100644
--- a/server/src/api/stripe/getSubscription.ts
+++ b/server/src/api/stripe/getSubscription.ts
@@ -242,7 +242,7 @@ export async function getSubscription(
const responseData = await getSubscriptionInner(organizationId);
return reply.send(responseData);
} catch (error: any) {
- console.error("Get Subscription Error:", error);
+ request.log.error({ err: error }, "Get Subscription Error");
// Handle specific Stripe errors if necessary
if (error instanceof Stripe.errors.StripeError) {
return reply.status(error.statusCode || 500).send({ error: error.message });
diff --git a/server/src/api/stripe/previewSubscriptionUpdate.ts b/server/src/api/stripe/previewSubscriptionUpdate.ts
index b70369a27..f82fe2107 100644
--- a/server/src/api/stripe/previewSubscriptionUpdate.ts
+++ b/server/src/api/stripe/previewSubscriptionUpdate.ts
@@ -164,7 +164,7 @@ export async function previewSubscriptionUpdate(
},
});
} catch (error: any) {
- console.error("Subscription Preview Error:", error);
+ request.log.error({ err: error }, "Subscription Preview Error");
return reply.status(500).send({
error: "Failed to preview subscription update",
details: error.message,
diff --git a/server/src/api/stripe/submitCancellationFeedback.ts b/server/src/api/stripe/submitCancellationFeedback.ts
index 23d9115ff..2820baee1 100644
--- a/server/src/api/stripe/submitCancellationFeedback.ts
+++ b/server/src/api/stripe/submitCancellationFeedback.ts
@@ -69,7 +69,7 @@ export async function submitCancellationFeedback(
return reply.send({ success: true });
} catch (error: any) {
- console.error("Cancellation Feedback Error:", error);
+ request.log.error({ err: error }, "Cancellation Feedback Error");
return reply.status(500).send({
error: "Failed to submit cancellation feedback",
});
diff --git a/server/src/api/stripe/updateSubscription.test.ts b/server/src/api/stripe/updateSubscription.test.ts
index c4c8c6e5c..dfc5f6410 100644
--- a/server/src/api/stripe/updateSubscription.test.ts
+++ b/server/src/api/stripe/updateSubscription.test.ts
@@ -57,7 +57,11 @@ function replyStub() {
}
function requestStub(userId: string | undefined, body: Record<string, unknown>) {
- return { user: userId ? { id: userId } : undefined, body } as any;
+ return {
+ user: userId ? { id: userId } : undefined,
+ body,
+ log: { error: vi.fn() },
+ } as any;
}
function fakeSubscription(status: "active" | "trialing", overrides: Record<string, unknown> = {}) {
diff --git a/server/src/api/stripe/updateSubscription.ts b/server/src/api/stripe/updateSubscription.ts
index f00de8b91..c6859117c 100644
--- a/server/src/api/stripe/updateSubscription.ts
+++ b/server/src/api/stripe/updateSubscription.ts
@@ -116,7 +116,7 @@ export async function updateSubscription(
},
});
} catch (error: any) {
- console.error("Subscription Update Error:", error);
+ request.log.error({ err: error }, "Subscription Update Error");
return reply.status(500).send({
error: "Failed to update subscription",
details: error.message,
diff --git a/server/src/api/stripe/webhook.test.ts b/server/src/api/stripe/webhook.test.ts
index 12e6d3eae..9a35ea99a 100644
--- a/server/src/api/stripe/webhook.test.ts
+++ b/server/src/api/stripe/webhook.test.ts
@@ -48,6 +48,12 @@ import { handleWebhook } from "./webhook.js";
const dialect = new PgDialect();
const SIGNATURE = "t=1700000000,v1=deadbeef";
+const requestLogger = {
+ debug: vi.fn(),
+ error: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+};
type RequestOverrides = {
rawBody?: string | Buffer | null;
@@ -61,6 +67,7 @@ function createRequest(overrides: RequestOverrides = {}) {
headers: overrides.headers ?? { "stripe-signature": SIGNATURE },
body: overrides.parsedBody,
raw: rawBody === null ? {} : { body: rawBody },
+ log: requestLogger,
} as any;
}
diff --git a/server/src/api/stripe/webhook.ts b/server/src/api/stripe/webhook.ts
index b16eae40b..1a75310d2 100644
--- a/server/src/api/stripe/webhook.ts
+++ b/server/src/api/stripe/webhook.ts
@@ -13,7 +13,7 @@ const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
export async function handleWebhook(request: FastifyRequest, reply: FastifyReply) {
if (!webhookSecret) {
- console.error("Stripe webhook secret is not configured.");
+ request.log.error("Stripe webhook secret is not configured");
return reply.status(500).send({ error: "Webhook secret not configured." });
}
@@ -29,7 +29,7 @@ export async function handleWebhook(request: FastifyRequest, reply: FastifyReply
event = (stripe as Stripe).webhooks.constructEvent(rawBody, sig as string, webhookSecret);
} catch (err: any) {
- console.error(`Webhook signature verification failed: ${err.message}`);
+ request.log.warn({ err }, "Stripe webhook signature verification failed");
return reply.status(400).send(`Webhook Error: ${err.message}`);
}
@@ -37,7 +37,7 @@ export async function handleWebhook(request: FastifyRequest, reply: FastifyReply
switch (event.type) {
case "checkout.session.completed":
const session = event.data.object as Stripe.Checkout.Session;
- console.log("Checkout session completed event received:", session.id);
+ request.log.info({ sessionId: session.id }, "Stripe checkout session completed");
// If the checkout session was for a subscription
if (session.mode === "subscription" && session.customer) {
@@ -59,16 +59,19 @@ export async function handleWebhook(request: FastifyRequest, reply: FastifyReply
// If the organization doesn't have the customer ID yet, update it
if (existingOrg.length === 0) {
- console.log(`Updating organization ${organizationId} with Stripe customer ID ${stripeCustomerId}`);
+ request.log.info({ organizationId, stripeCustomerId }, "Linking organization to Stripe customer");
await db
.update(organization)
.set({ stripeCustomerId: stripeCustomerId })
.where(eq(organization.id, organizationId));
} else {
- console.log(`Organization ${existingOrg[0].id} already has Stripe customer ID ${stripeCustomerId}`);
+ request.log.info(
+ { organizationId: existingOrg[0].id, stripeCustomerId },
+ "Organization already linked to Stripe customer"
+ );
}
} catch (dbError: any) {
- console.error(`Database error updating organization with Stripe customer ID: ${dbError.message}`);
+ request.log.error({ err: dbError, stripeCustomerId }, "Failed to link organization to Stripe customer");
// Retriable failure: the org is still not linked to its Stripe customer.
// Return a 5xx so Stripe retries the webhook; acking here would drop the
// event permanently and leave the organization unlinked forever.
@@ -78,8 +81,9 @@ export async function handleWebhook(request: FastifyRequest, reply: FastifyReply
// Non-retriable: the checkout session itself lacks organizationId metadata,
// so a Stripe retry would deliver the exact same payload. Ack with 200 and
// log — retrying can never fix this.
- console.error(
- `Missing required metadata in checkout session ${session.id}. Customer ID: ${stripeCustomerId}, Organization ID: ${organizationId}`
+ request.log.warn(
+ { sessionId: session.id, stripeCustomerId, organizationId },
+ "Stripe checkout session is missing required metadata"
);
}
}
@@ -99,7 +103,7 @@ export async function handleWebhook(request: FastifyRequest, reply: FastifyReply
// ... handle other event types as needed
default:
- console.log(`Unhandled event type ${event.type}`);
+ request.log.debug({ eventType: event.type }, "Ignoring unhandled Stripe webhook event");
}
// Return a 200 response to acknowledge receipt of the event
diff --git a/server/src/api/teams/createTeam.ts b/server/src/api/teams/createTeam.ts
index 340aa90dd..26ffbc019 100644
--- a/server/src/api/teams/createTeam.ts
+++ b/server/src/api/teams/createTeam.ts
@@ -1,13 +1,7 @@
import { eq, and, inArray } from "drizzle-orm";
import { FastifyReply, FastifyRequest } from "fastify";
import { db } from "../../db/postgres/postgres.js";
-import {
- team,
- teamMember,
- teamSiteAccess,
- member,
- sites,
-} from "../../db/postgres/schema.js";
+import { team, teamMember, teamSiteAccess, member, sites } from "../../db/postgres/schema.js";
import { invalidateSitesAccessCache } from "../../lib/auth-utils.js";
interface CreateTeamBody {
@@ -36,14 +30,9 @@ export async function createTeam(
const orgMembers = await db
.select({ userId: member.userId })
.from(member)
- .where(
- and(
- eq(member.organizationId, organizationId),
- inArray(member.userId, memberUserIds)
- )
- );
- const validUserIds = new Set(orgMembers.map((m) => m.userId));
- const invalidUserIds = memberUserIds.filter((id) => !validUserIds.has(id));
+ .where(and(eq(member.organizationId, organizationId), inArray(member.userId, memberUserIds)));
+ const validUserIds = new Set(orgMembers.map(m => m.userId));
+ const invalidUserIds = memberUserIds.filter(id => !validUserIds.has(id));
if (invalidUserIds.length > 0) {
return reply.status(400).send({
error: `Users not in organization: ${invalidUserIds.join(", ")}`,
@@ -56,14 +45,9 @@ export async function createTeam(
const orgSites = await db
.select({ siteId: sites.siteId })
.from(sites)
- .where(
- and(
- eq(sites.organizationId, organizationId),
- inArray(sites.siteId, siteIds)
- )
- );
- const validSiteIds = new Set(orgSites.map((s) => s.siteId));
- const invalidSiteIds = siteIds.filter((id) => !validSiteIds.has(id));
+ .where(and(eq(sites.organizationId, organizationId), inArray(sites.siteId, siteIds)));
+ const validSiteIds = new Set(orgSites.map(s => s.siteId));
+ const invalidSiteIds = siteIds.filter(id => !validSiteIds.has(id));
if (invalidSiteIds.length > 0) {
return reply.status(400).send({
error: `Sites not in organization: ${invalidSiteIds.join(", ")}`,
@@ -74,7 +58,7 @@ export async function createTeam(
const teamId = crypto.randomUUID();
const now = new Date().toISOString();
- await db.transaction(async (tx) => {
+ await db.transaction(async tx => {
// Insert team
await tx.insert(team).values({
id: teamId,
@@ -87,7 +71,7 @@ export async function createTeam(
// Insert team members
if (memberUserIds && memberUserIds.length > 0) {
await tx.insert(teamMember).values(
- memberUserIds.map((userId) => ({
+ memberUserIds.map(userId => ({
id: crypto.randomUUID(),
teamId,
userId,
@@ -99,7 +83,7 @@ export async function createTeam(
// Insert team site access
if (siteIds && siteIds.length > 0) {
await tx.insert(teamSiteAccess).values(
- siteIds.map((siteId) => ({
+ siteIds.map(siteId => ({
teamId,
siteId,
}))
@@ -124,7 +108,7 @@ export async function createTeam(
siteIds: siteIds || [],
});
} catch (error) {
- console.error("Error creating team:", error);
+ request.log.error({ err: error }, "Error creating team");
return reply.status(500).send({ error: "Failed to create team" });
}
}
diff --git a/server/src/api/teams/deleteTeam.ts b/server/src/api/teams/deleteTeam.ts
index f4c18b7d6..50632c509 100644
--- a/server/src/api/teams/deleteTeam.ts
+++ b/server/src/api/teams/deleteTeam.ts
@@ -31,9 +31,7 @@ export async function deleteTeam(
.where(eq(teamMember.teamId, teamId));
// Delete team (cascades to teamMember and teamSiteAccess)
- await db
- .delete(team)
- .where(and(eq(team.id, teamId), eq(team.organizationId, organizationId)));
+ await db.delete(team).where(and(eq(team.id, teamId), eq(team.organizationId, organizationId)));
// Invalidate cache for affected users
for (const m of affectedMembers) {
@@ -42,7 +40,7 @@ export async function deleteTeam(
return reply.status(200).send({ success: true });
} catch (error) {
- console.error("Error deleting team:", error);
+ request.log.error({ err: error }, "Error deleting team");
return reply.status(500).send({ error: "Failed to delete team" });
}
}
diff --git a/server/src/api/teams/listTeams.ts b/server/src/api/teams/listTeams.ts
index 00a0ae1a7..e87680d9d 100644
--- a/server/src/api/teams/listTeams.ts
+++ b/server/src/api/teams/listTeams.ts
@@ -1,14 +1,7 @@
import { eq, and, inArray } from "drizzle-orm";
import { FastifyReply, FastifyRequest } from "fastify";
import { db } from "../../db/postgres/postgres.js";
-import {
- team,
- teamMember,
- teamSiteAccess,
- sites,
- member,
- user,
-} from "../../db/postgres/schema.js";
+import { team, teamMember, teamSiteAccess, sites, member, user } from "../../db/postgres/schema.js";
import { getUserIdFromRequest } from "../../lib/auth-utils.js";
export async function listTeams(
@@ -26,24 +19,15 @@ export async function listTeams(
? await db
.select({ id: member.id, role: member.role })
.from(member)
- .where(
- and(
- eq(member.organizationId, organizationId),
- eq(member.userId, userId)
- )
- )
+ .where(and(eq(member.organizationId, organizationId), eq(member.userId, userId)))
.limit(1)
: [];
const isAdminOrOwner =
- memberRecord.length > 0 &&
- (memberRecord[0].role === "admin" || memberRecord[0].role === "owner");
+ memberRecord.length > 0 && (memberRecord[0].role === "admin" || memberRecord[0].role === "owner");
// Get all teams in the org
- let teamsData = await db
- .select()
- .from(team)
- .where(eq(team.organizationId, organizationId));
+ let teamsData = await db.select().from(team).where(eq(team.organizationId, organizationId));
// If not admin/owner, filter to only teams the user belongs to
if (!isAdminOrOwner && userId) {
@@ -52,15 +36,15 @@ export async function listTeams(
.from(teamMember)
.where(eq(teamMember.userId, userId));
- const userTeamIdSet = new Set(userTeamIds.map((t) => t.teamId));
- teamsData = teamsData.filter((t) => userTeamIdSet.has(t.id));
+ const userTeamIdSet = new Set(userTeamIds.map(t => t.teamId));
+ teamsData = teamsData.filter(t => userTeamIdSet.has(t.id));
}
if (teamsData.length === 0) {
return reply.send({ teams: [] });
}
- const teamIds = teamsData.map((t) => t.id);
+ const teamIds = teamsData.map(t => t.id);
// Fetch members and sites for all teams in parallel
const [membersData, sitesData] = await Promise.all([
@@ -87,10 +71,7 @@ export async function listTeams(
]);
// Build lookup maps
- const membersMap = new Map<
- string,
- { userId: string; userName: string | null; userEmail: string }[]
- >();
+ const membersMap = new Map<string, { userId: string; userName: string | null; userEmail: string }[]>();
for (const m of membersData) {
const existing = membersMap.get(m.teamId) || [];
existing.push({
@@ -101,10 +82,7 @@ export async function listTeams(
membersMap.set(m.teamId, existing);
}
- const sitesMap = new Map<
- string,
- { siteId: number; domain: string; name: string }[]
- >();
+ const sitesMap = new Map<string, { siteId: number; domain: string; name: string }[]>();
for (const s of sitesData) {
const existing = sitesMap.get(s.teamId) || [];
existing.push({ siteId: s.siteId, domain: s.domain, name: s.name });
@@ -112,7 +90,7 @@ export async function listTeams(
}
return reply.send({
- teams: teamsData.map((t) => ({
+ teams: teamsData.map(t => ({
id: t.id,
name: t.name,
organizationId: t.organizationId,
@@ -123,7 +101,7 @@ export async function listTeams(
})),
});
} catch (error) {
- console.error("Error listing teams:", error);
+ request.log.error({ err: error }, "Error listing teams");
return reply.status(500).send({ error: "Failed to list teams" });
}
}
diff --git a/server/src/api/teams/updateTeam.ts b/server/src/api/teams/updateTeam.ts
index 2cb5bd64e..e9b2b385c 100644
--- a/server/src/api/teams/updateTeam.ts
+++ b/server/src/api/teams/updateTeam.ts
@@ -1,13 +1,7 @@
import { eq, and, inArray } from "drizzle-orm";
import { FastifyReply, FastifyRequest } from "fastify";
import { db } from "../../db/postgres/postgres.js";
-import {
- team,
- teamMember,
- teamSiteAccess,
- member,
- sites,
-} from "../../db/postgres/schema.js";
+import { team, teamMember, teamSiteAccess, member, sites } from "../../db/postgres/schema.js";
import { invalidateSitesAccessCache } from "../../lib/auth-utils.js";
interface UpdateTeamBody {
@@ -43,21 +37,16 @@ export async function updateTeam(
.select({ userId: teamMember.userId })
.from(teamMember)
.where(eq(teamMember.teamId, teamId));
- const existingUserIds = existingMembers.map((m) => m.userId);
+ const existingUserIds = existingMembers.map(m => m.userId);
// Validate memberUserIds are org members
if (memberUserIds && memberUserIds.length > 0) {
const orgMembers = await db
.select({ userId: member.userId })
.from(member)
- .where(
- and(
- eq(member.organizationId, organizationId),
- inArray(member.userId, memberUserIds)
- )
- );
- const validUserIds = new Set(orgMembers.map((m) => m.userId));
- const invalidUserIds = memberUserIds.filter((id) => !validUserIds.has(id));
+ .where(and(eq(member.organizationId, organizationId), inArray(member.userId, memberUserIds)));
+ const validUserIds = new Set(orgMembers.map(m => m.userId));
+ const invalidUserIds = memberUserIds.filter(id => !validUserIds.has(id));
if (invalidUserIds.length > 0) {
return reply.status(400).send({
error: `Users not in organization: ${invalidUserIds.join(", ")}`,
@@ -70,14 +59,9 @@ export async function updateTeam(
const orgSites = await db
.select({ siteId: sites.siteId })
.from(sites)
- .where(
- and(
- eq(sites.organizationId, organizationId),
- inArray(sites.siteId, siteIds)
- )
- );
- const validSiteIds = new Set(orgSites.map((s) => s.siteId));
- const invalidSiteIds = siteIds.filter((id) => !validSiteIds.has(id));
+ .where(and(eq(sites.organizationId, organizationId), inArray(sites.siteId, siteIds)));
+ const validSiteIds = new Set(orgSites.map(s => s.siteId));
+ const invalidSiteIds = siteIds.filter(id => !validSiteIds.has(id));
if (invalidSiteIds.length > 0) {
return reply.status(400).send({
error: `Sites not in organization: ${invalidSiteIds.join(", ")}`,
@@ -87,7 +71,7 @@ export async function updateTeam(
const now = new Date().toISOString();
- await db.transaction(async (tx) => {
+ await db.transaction(async tx => {
// Update team name
const updates: Record<string, string> = { updatedAt: now };
if (name !== undefined) {
@@ -100,7 +84,7 @@ export async function updateTeam(
await tx.delete(teamMember).where(eq(teamMember.teamId, teamId));
if (memberUserIds.length > 0) {
await tx.insert(teamMember).values(
- memberUserIds.map((userId) => ({
+ memberUserIds.map(userId => ({
id: crypto.randomUUID(),
teamId,
userId,
@@ -112,12 +96,10 @@ export async function updateTeam(
// Replace sites if provided
if (siteIds !== undefined) {
- await tx
- .delete(teamSiteAccess)
- .where(eq(teamSiteAccess.teamId, teamId));
+ await tx.delete(teamSiteAccess).where(eq(teamSiteAccess.teamId, teamId));
if (siteIds.length > 0) {
await tx.insert(teamSiteAccess).values(
- siteIds.map((siteId) => ({
+ siteIds.map(siteId => ({
teamId,
siteId,
}))
@@ -127,17 +109,14 @@ export async function updateTeam(
});
// Invalidate cache for all affected users (old + new members)
- const allAffectedUserIds = new Set([
- ...existingUserIds,
- ...(memberUserIds || []),
- ]);
+ const allAffectedUserIds = new Set([...existingUserIds, ...(memberUserIds || [])]);
for (const userId of allAffectedUserIds) {
invalidateSitesAccessCache(userId);
}
return reply.status(200).send({ success: true });
} catch (error) {
- console.error("Error updating team:", error);
+ request.log.error({ err: error }, "Error updating team");
return reply.status(500).send({ error: "Failed to update team" });
}
}
diff --git a/server/src/api/uptime/createMonitor.ts b/server/src/api/uptime/createMonitor.ts
index 0293721bf..1b842c2e5 100644
--- a/server/src/api/uptime/createMonitor.ts
+++ b/server/src/api/uptime/createMonitor.ts
@@ -84,7 +84,7 @@ export async function createMonitor(request: FastifyRequest<CreateMonitorBody>,
details: zodError.errors,
});
}
- console.error("Error creating monitor:", error);
+ request.log.error({ err: error }, "Error creating monitor");
return reply.status(500).send({ error: "Internal server error" });
}
}
diff --git a/server/src/api/uptime/deleteMonitor.ts b/server/src/api/uptime/deleteMonitor.ts
index fad19b84c..c16db01bc 100644
--- a/server/src/api/uptime/deleteMonitor.ts
+++ b/server/src/api/uptime/deleteMonitor.ts
@@ -53,7 +53,7 @@ export async function deleteMonitor(request: FastifyRequest<DeleteMonitorParams>
return reply.status(204).send();
} catch (error) {
- console.error("Error deleting monitor:", error);
+ request.log.error({ err: error }, "Error deleting monitor");
return reply.status(500).send({ error: "Internal server error" });
}
}
diff --git a/server/src/api/uptime/getMonitor.ts b/server/src/api/uptime/getMonitor.ts
index 6ca696b8a..148313820 100644
--- a/server/src/api/uptime/getMonitor.ts
+++ b/server/src/api/uptime/getMonitor.ts
@@ -56,7 +56,7 @@ export async function getMonitor(request: FastifyRequest<GetMonitorParams>, repl
return reply.status(200).send(monitorWithStatus);
} catch (error) {
- console.error("Error retrieving monitor:", error);
+ request.log.error({ err: error }, "Error retrieving monitor");
return reply.status(500).send({ error: "Internal server error" });
}
}
diff --git a/server/src/api/uptime/getMonitorEvents.ts b/server/src/api/uptime/getMonitorEvents.ts
index 2f2e17531..a385c2cef 100644
--- a/server/src/api/uptime/getMonitorEvents.ts
+++ b/server/src/api/uptime/getMonitorEvents.ts
@@ -142,7 +142,7 @@ export async function getMonitorEvents(request: FastifyRequest<GetMonitorEventsR
details: zodError.errors,
});
}
- console.error("Error retrieving monitor events:", error);
+ request.log.error({ err: error }, "Error retrieving monitor events");
return reply.status(500).send({ error: "Internal server error" });
}
}
diff --git a/server/src/api/uptime/getMonitorStats.ts b/server/src/api/uptime/getMonitorStats.ts
index 66fb2dc62..1868d3b8a 100644
--- a/server/src/api/uptime/getMonitorStats.ts
+++ b/server/src/api/uptime/getMonitorStats.ts
@@ -211,7 +211,7 @@ export async function getMonitorStats(request: FastifyRequest<GetMonitorStatsReq
details: zodError.errors,
});
}
- console.error("Error retrieving monitor stats:", error);
+ request.log.error({ err: error }, "Error retrieving monitor stats");
return reply.status(500).send({ error: "Internal server error" });
}
}
diff --git a/server/src/api/uptime/getMonitorStatus.ts b/server/src/api/uptime/getMonitorStatus.ts
index d10787f09..0044e4adc 100644
--- a/server/src/api/uptime/getMonitorStatus.ts
+++ b/server/src/api/uptime/getMonitorStatus.ts
@@ -129,7 +129,7 @@ export async function getMonitorStatus(request: FastifyRequest<GetMonitorStatusR
recentChecks,
});
} catch (error) {
- console.error("Error retrieving monitor status:", error);
+ request.log.error({ err: error }, "Error retrieving monitor status");
return reply.status(500).send({ error: "Internal server error" });
}
}
diff --git a/server/src/api/uptime/getMonitorUptime.ts b/server/src/api/uptime/getMonitorUptime.ts
index 42171ddf0..9951c18bb 100644
--- a/server/src/api/uptime/getMonitorUptime.ts
+++ b/server/src/api/uptime/getMonitorUptime.ts
@@ -180,7 +180,7 @@ export async function getMonitorUptime(request: FastifyRequest<GetMonitorUptimeR
failedChecks: stats.total_downtime_checks,
});
} catch (error) {
- console.error("Error retrieving monitor uptime:", error);
+ request.log.error({ err: error }, "Error retrieving monitor uptime");
return reply.status(500).send({ error: "Internal server error" });
}
}
diff --git a/server/src/api/uptime/getMonitorUptimeBuckets.ts b/server/src/api/uptime/getMonitorUptimeBuckets.ts
index bdf4c2e54..3703e9a34 100644
--- a/server/src/api/uptime/getMonitorUptimeBuckets.ts
+++ b/server/src/api/uptime/getMonitorUptimeBuckets.ts
@@ -203,7 +203,7 @@ export async function getMonitorUptimeBuckets(
details: zodError.errors,
});
}
- console.error("Error retrieving monitor uptime buckets:", error);
+ request.log.error({ err: error }, "Error retrieving monitor uptime buckets");
return reply.status(500).send({ error: "Internal server error" });
}
}
diff --git a/server/src/api/uptime/getMonitors.ts b/server/src/api/uptime/getMonitors.ts
index 2fe24b4e0..9a7e3baee 100644
--- a/server/src/api/uptime/getMonitors.ts
+++ b/server/src/api/uptime/getMonitors.ts
@@ -139,7 +139,7 @@ export async function getMonitors(request: FastifyRequest<GetMonitorsRequest>, r
});
});
} catch (error) {
- console.error("Error calculating uptime percentages:", error);
+ request.log.error({ err: error }, "Error calculating uptime percentages");
// Continue without uptime data rather than failing the entire request
}
}
@@ -165,7 +165,7 @@ export async function getMonitors(request: FastifyRequest<GetMonitorsRequest>, r
details: zodError.errors,
});
}
- console.error("Error retrieving monitors:", error);
+ request.log.error({ err: error }, "Error retrieving monitors");
return reply.status(500).send({ error: "Internal server error" });
}
}
diff --git a/server/src/api/uptime/getRegions.ts b/server/src/api/uptime/getRegions.ts
index 6cb249ebc..dafe6dcb6 100644
--- a/server/src/api/uptime/getRegions.ts
+++ b/server/src/api/uptime/getRegions.ts
@@ -39,7 +39,7 @@ export async function getRegions(request: FastifyRequest, reply: FastifyReply) {
regions: formattedRegions,
});
} catch (error) {
- console.error("Error fetching regions:", error);
+ request.log.error({ err: error }, "Error fetching regions");
return reply.status(500).send({ error: "Failed to fetch regions" });
}
}
diff --git a/server/src/api/uptime/notifications.ts b/server/src/api/uptime/notifications.ts
index bff870465..c5c904b77 100644
--- a/server/src/api/uptime/notifications.ts
+++ b/server/src/api/uptime/notifications.ts
@@ -277,7 +277,7 @@ export const notificationRoutes = async (server: FastifyInstance) => {
message: `Test notification sent to ${channel.type} channel: ${channel.name}`,
});
} catch (error) {
- console.error("Failed to send test notification:", error);
+ request.log.error({ err: error }, "Failed to send test notification");
return reply.code(500).send({
success: false,
message: "Failed to send test notification",
diff --git a/server/src/api/uptime/updateMonitor.ts b/server/src/api/uptime/updateMonitor.ts
index 8b6495b13..cfe5a3e44 100644
--- a/server/src/api/uptime/updateMonitor.ts
+++ b/server/src/api/uptime/updateMonitor.ts
@@ -87,7 +87,7 @@ export async function updateMonitor(request: FastifyRequest<UpdateMonitorRequest
details: zodError.errors,
});
}
- console.error("Error updating monitor:", error);
+ request.log.error({ err: error }, "Error updating monitor");
return reply.status(500).send({ error: "Internal server error" });
}
}
diff --git a/server/src/api/user/addUserToOrganization.ts b/server/src/api/user/addUserToOrganization.ts
index 831771f3d..cb0b8ed1e 100644
--- a/server/src/api/user/addUserToOrganization.ts
+++ b/server/src/api/user/addUserToOrganization.ts
@@ -97,7 +97,7 @@ export async function addUserToOrganization(request: FastifyRequest<AddUserToOrg
message: "User added to organization successfully",
});
} catch (error: any) {
- console.error(String(error));
+ request.log.error({ err: error }, "Error adding user to organization");
return reply.status(500).send({ error: String(error) });
}
}
diff --git a/server/src/api/user/createApiKey.ts b/server/src/api/user/createApiKey.ts
index 48c807c61..cc66f5a0c 100644
--- a/server/src/api/user/createApiKey.ts
+++ b/server/src/api/user/createApiKey.ts
@@ -5,12 +5,7 @@ import { auth } from "../../lib/auth.js";
import { getSessionFromReq } from "../../lib/auth-utils.js";
import { apiKeyPermissionsSchema } from "../../lib/scopes.js";
import { getSubscriptionInner } from "../stripe/getSubscription.js";
-import {
- API_RATE_LIMIT_WINDOW,
- IS_CLOUD,
- PRO_API_RATE_LIMIT,
- STANDARD_API_RATE_LIMIT,
-} from "../../lib/const.js";
+import { API_RATE_LIMIT_WINDOW, IS_CLOUD, PRO_API_RATE_LIMIT, STANDARD_API_RATE_LIMIT } from "../../lib/const.js";
const createApiKeyBodySchema = z.object({
name: z.string().trim().min(1, "Name is required"),
@@ -62,10 +57,7 @@ export async function createUserApiKey(
rateLimitEnabled = true;
rateLimitTimeWindow = API_RATE_LIMIT_WINDOW;
- rateLimitMax =
- planName.includes("pro") || planName === "custom"
- ? PRO_API_RATE_LIMIT
- : STANDARD_API_RATE_LIMIT;
+ rateLimitMax = planName.includes("pro") || planName === "custom" ? PRO_API_RATE_LIMIT : STANDARD_API_RATE_LIMIT;
}
const keyLimit = apiKeyLimitForPlan(planName);
@@ -96,10 +88,15 @@ export async function createUserApiKey(
// Surface better-auth's own 4xx rejections by message; anything else stays
// a generic 500 so internal error detail never reaches the client.
const err = error as { name?: string; statusCode?: unknown; message?: string };
- if (err?.name === "APIError" && typeof err.statusCode === "number" && err.statusCode >= 400 && err.statusCode < 500) {
+ if (
+ err?.name === "APIError" &&
+ typeof err.statusCode === "number" &&
+ err.statusCode >= 400 &&
+ err.statusCode < 500
+ ) {
return reply.status(err.statusCode).send({ error: err.message || "Failed to create API key" });
}
- console.error("Error creating API key:", error);
+ request.log.error({ err: error }, "Error creating API key");
return reply.status(500).send({ error: "Failed to create API key" });
}
}
diff --git a/server/src/api/user/createOrgApiKey.ts b/server/src/api/user/createOrgApiKey.ts
index ae1c20d3e..281e33fa0 100644
--- a/server/src/api/user/createOrgApiKey.ts
+++ b/server/src/api/user/createOrgApiKey.ts
@@ -3,12 +3,7 @@ import { z } from "zod";
import { apiKeyLimitForPlan, createApiKeyWithinLimit } from "../../lib/apiKeyLimits.js";
import { auth } from "../../lib/auth.js";
import { ORG_API_KEY_CONFIG_ID } from "../../lib/bearerAuth.js";
-import {
- API_RATE_LIMIT_WINDOW,
- IS_CLOUD,
- PRO_API_RATE_LIMIT,
- STANDARD_API_RATE_LIMIT,
-} from "../../lib/const.js";
+import { API_RATE_LIMIT_WINDOW, IS_CLOUD, PRO_API_RATE_LIMIT, STANDARD_API_RATE_LIMIT } from "../../lib/const.js";
import { apiKeyPermissionsSchema } from "../../lib/scopes.js";
import { getSubscriptionInner } from "../stripe/getSubscription.js";
@@ -70,8 +65,7 @@ export async function createOrgApiKey(
rateLimitEnabled = true;
rateLimitTimeWindow = API_RATE_LIMIT_WINDOW;
- rateLimitMax =
- planName.includes("pro") || planName === "custom" ? PRO_API_RATE_LIMIT : STANDARD_API_RATE_LIMIT;
+ rateLimitMax = planName.includes("pro") || planName === "custom" ? PRO_API_RATE_LIMIT : STANDARD_API_RATE_LIMIT;
}
const keyLimit = apiKeyLimitForPlan(planName);
@@ -106,10 +100,15 @@ export async function createOrgApiKey(
// validation) by message; anything else stays a generic 500 so internal
// error detail never reaches the client.
const err = error as { name?: string; statusCode?: unknown; message?: string };
- if (err?.name === "APIError" && typeof err.statusCode === "number" && err.statusCode >= 400 && err.statusCode < 500) {
+ if (
+ err?.name === "APIError" &&
+ typeof err.statusCode === "number" &&
+ err.statusCode >= 400 &&
+ err.statusCode < 500
+ ) {
return reply.status(err.statusCode).send({ error: err.message || "Failed to create API key" });
}
- console.error("Error creating organization API key:", error);
+ request.log.error({ err: error }, "Error creating organization API key");
return reply.status(500).send({ error: "Failed to create API key" });
}
}
diff --git a/server/src/api/user/createUserInOrganization.ts b/server/src/api/user/createUserInOrganization.ts
index 11b43a62d..ea6d32651 100644
--- a/server/src/api/user/createUserInOrganization.ts
+++ b/server/src/api/user/createUserInOrganization.ts
@@ -37,10 +37,7 @@ interface CreateUserInOrganization {
* better-auth's internal adapter so password hashing and account linking match
* the admin plugin exactly.
*/
-export async function createUserInOrganization(
- request: FastifyRequest<CreateUserInOrganization>,
- reply: FastifyReply
-) {
+export async function createUserInOrganization(request: FastifyRequest<CreateUserInOrganization>, reply: FastifyReply) {
try {
const { organizationId } = request.params;
const { email: rawEmail, name, password, role } = request.body;
@@ -121,7 +118,7 @@ export async function createUserInOrganization(
return reply.status(201).send({ message: "User created and added to organization successfully" });
} catch (error: any) {
- console.error(String(error));
+ request.log.error({ err: error }, "Error creating user in organization");
return reply.status(500).send({ error: String(error) });
}
}
diff --git a/server/src/api/user/getMyOrganizations.ts b/server/src/api/user/getMyOrganizations.ts
index eb3abcc17..0d43d2ed9 100644
--- a/server/src/api/user/getMyOrganizations.ts
+++ b/server/src/api/user/getMyOrganizations.ts
@@ -131,7 +131,7 @@ export const getMyOrganizations = async (request: FastifyRequest, reply: Fastify
return reply.send(organizationsWithMembersAndSites);
} catch (error) {
- console.error("Error fetching organizations with members:", error);
+ request.log.error({ err: error }, "Error fetching organizations with members");
return reply.status(500).send({ error: "Failed to fetch organizations" });
}
};
diff --git a/server/src/api/user/getUserOrganizations.ts b/server/src/api/user/getUserOrganizations.ts
index 335a7a69a..dda4c886f 100644
--- a/server/src/api/user/getUserOrganizations.ts
+++ b/server/src/api/user/getUserOrganizations.ts
@@ -26,7 +26,7 @@ export const getUserOrganizations = async (request: FastifyRequest, reply: Fasti
return reply.send(userOrganizations);
} catch (error) {
- console.error("Error fetching user organizations:", error);
+ request.log.error({ err: error }, "Error fetching user organizations");
return reply.status(500).send("Failed to fetch user organizations");
}
};
diff --git a/server/src/api/user/listOrganizationMembers.ts b/server/src/api/user/listOrganizationMembers.ts
index fa854d377..76ac4e55c 100644
--- a/server/src/api/user/listOrganizationMembers.ts
+++ b/server/src/api/user/listOrganizationMembers.ts
@@ -97,7 +97,7 @@ export async function listOrganizationMembers(
})),
});
} catch (error) {
- console.error("Error listing organization members:", error);
+ request.log.error({ err: error }, "Error listing organization members");
return reply.status(500).send({
error: "InternalServerError",
message: "An error occurred while listing organization members",
diff --git a/server/src/api/user/unsubscribeMarketing.ts b/server/src/api/user/unsubscribeMarketing.ts
index b9d470b84..77c8a2b57 100644
--- a/server/src/api/user/unsubscribeMarketing.ts
+++ b/server/src/api/user/unsubscribeMarketing.ts
@@ -7,10 +7,7 @@ import { unsubscribeContact, cancelScheduledEmail } from "../../lib/email/email.
import { onboardingTipsService } from "../../services/onboardingTips/onboardingTipsService.js";
// Authenticated user unsubscribe
-export const unsubscribeMarketing = async (
- request: FastifyRequest,
- reply: FastifyReply
-) => {
+export const unsubscribeMarketing = async (request: FastifyRequest, reply: FastifyReply) => {
try {
const userId = request.user?.id;
if (!userId) {
@@ -48,7 +45,7 @@ export const unsubscribeMarketing = async (
return reply.send({ success: true, message: "Successfully unsubscribed from marketing emails" });
} catch (error) {
- console.error("Error unsubscribing from marketing emails:", error);
+ request.log.error({ err: error }, "Error unsubscribing from marketing emails");
return reply.status(500).send({ error: "Failed to unsubscribe" });
}
};
@@ -121,7 +118,7 @@ export const oneClickUnsubscribeMarketing = async (
// For POST requests (email client List-Unsubscribe), return 200 OK as per RFC 8058
return reply.status(200).send();
} catch (error) {
- console.error("Error in one-click unsubscribe:", error);
+ request.log.error({ err: error }, "Error in one-click unsubscribe");
// Still return 200 to not confuse email clients
return reply.status(200).send();
}
diff --git a/server/src/api/user/updateAccountSettings.ts b/server/src/api/user/updateAccountSettings.ts
index fa10630de..917ee9790 100644
--- a/server/src/api/user/updateAccountSettings.ts
+++ b/server/src/api/user/updateAccountSettings.ts
@@ -63,7 +63,7 @@ export const updateAccountSettings = async (
},
});
} catch (error) {
- console.error("Error updating account settings:", error);
+ request.log.error({ err: error }, "Error updating account settings");
return reply.status(500).send({ error: "Failed to update account settings" });
}
};
diff --git a/server/src/index.ts b/server/src/index.ts
index e9bd1a9bf..3d5b6ffae 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -175,6 +175,7 @@ import { oauthWellKnownRoutes } from "./mcp/wellKnown.js";
import { createCorsOptionsDelegate, createRejectUntrustedOriginHook } from "./lib/cors.js";
import { IS_CLOUD } from "./lib/const.js";
import { logger } from "./lib/logger/logger.js";
+import { registerRequestLogging } from "./lib/logger/requestLogging.js";
import { reengagementService } from "./services/reengagement/reengagementService.js";
import { telemetryService } from "./services/telemetryService.js";
import { handleIdentify } from "./services/tracker/identifyService.js";
@@ -269,6 +270,8 @@ const server = Fastify({
bodyLimit: 10 * 1024 * 1024, // 10MB limit for session replay data
});
+registerRequestLogging(server);
+
server.register(cors, {
delegator: createCorsOptionsDelegate(),
});
diff --git a/server/src/lib/logger/LOGGING.md b/server/src/lib/logger/LOGGING.md
index 46d3d118e..880f69bbf 100644
--- a/server/src/lib/logger/LOGGING.md
+++ b/server/src/lib/logger/LOGGING.md
@@ -29,7 +29,18 @@ export async function getUsers(request: FastifyRequest, reply: FastifyReply) {
}
```
-Automatic Fastify request logging is currently disabled. Do not assume that every request produces a completion or duration event.
+Fastify's default request logging is disabled and replaced by `requestLogging.ts`. The replacement emits one lifecycle event per request with `method`, `url`, `route`, `statusCode`, `responseTimeMs`, and Fastify's bound `reqId`.
+
+| Outcome | Level | Message |
+| -------------------------------------------- | ------- | ------------------------------------- |
+| thrown server failure | `error` | `Request failed` with `err` |
+| thrown client failure | `warn` | `Request failed` with `err` |
+| handled response with status 500 or greater | `error` | `Request completed with server error` |
+| handled response with status 400–499 | `warn` | `Request completed with client error` |
+| successful response | `info` | `Request completed` |
+| successful ingestion or static-asset request | `debug` | `Request completed` |
+
+Routes configured with `logLevel: "silent"`, such as health checks, emit no lifecycle event. Thrown failures are marked internally so the later response hook does not log the same lifecycle failure twice.
## Background Modules
@@ -74,11 +85,11 @@ Never log passwords, tokens, cookies, authentication headers, raw credentials, o
## Legacy Calls
-Direct `console` logging still exists in the server. New and modified code should use:
+Route and MCP modules no longer use direct `console` logging or the process-wide logger. Direct `console` logging still exists elsewhere in the server. New and modified code should use:
- `request.log` for request-bound work
- `server.log` for Fastify lifecycle work
- `createServiceLogger` for background modules
- `logger` for process-wide work
-Migrating existing `console` calls and adding HTTP lifecycle events are separate refactors from the shared runtime.
+Remaining `console` migration in background modules is separate from request lifecycle logging.
diff --git a/server/src/lib/logger/requestLogging.test.ts b/server/src/lib/logger/requestLogging.test.ts
new file mode 100644
index 000000000..aa20a420e
--- /dev/null
+++ b/server/src/lib/logger/requestLogging.test.ts
@@ -0,0 +1,123 @@
+import Fastify, { type FastifyInstance } from "fastify";
+import { pino } from "pino";
+import { afterEach, describe, expect, it } from "vitest";
+import { registerRequestLogging } from "./requestLogging.js";
+
+type LogEvent = Record<string, unknown>;
+
+const apps: Array<ReturnType<typeof Fastify>> = [];
+
+function createApp() {
+ const events: LogEvent[] = [];
+ const logger = pino(
+ { base: undefined, level: "trace", timestamp: false },
+ {
+ write(line: string) {
+ events.push(JSON.parse(line) as LogEvent);
+ },
+ }
+ );
+ const app = Fastify({ disableRequestLogging: true, loggerInstance: logger });
+ registerRequestLogging(app as unknown as FastifyInstance);
+ apps.push(app);
+
+ return { app, events };
+}
+
+function requestEvents(events: LogEvent[]) {
+ return events.filter(event => typeof event.msg === "string" && event.msg.startsWith("Request "));
+}
+
+afterEach(async () => {
+ await Promise.all(apps.splice(0).map(app => app.close()));
+});
+
+describe("request lifecycle logging", () => {
+ it("logs successful requests with correlation and timing context", async () => {
+ const { app, events } = createApp();
+ app.get("/sites/:siteId", (_request, reply) => reply.status(204).send());
+
+ await app.inject({ method: "GET", url: "/sites/42?token=secret" });
+
+ expect(requestEvents(events)).toEqual([
+ expect.objectContaining({
+ level: 30,
+ method: "GET",
+ url: "/sites/42",
+ route: "/sites/:siteId",
+ statusCode: 204,
+ reqId: "req-1",
+ responseTimeMs: expect.any(Number),
+ msg: "Request completed",
+ }),
+ ]);
+ });
+
+ it("logs successful ingestion requests at debug", async () => {
+ const { app, events } = createApp();
+ app.post("/api/track", () => ({ success: true }));
+
+ await app.inject({ method: "POST", url: "/api/track" });
+
+ expect(requestEvents(events)).toEqual([
+ expect.objectContaining({ level: 20, route: "/api/track", statusCode: 200, msg: "Request completed" }),
+ ]);
+ });
+
+ it("logs handled response failures from their status code", async () => {
+ const { app, events } = createApp();
+ app.get("/unavailable", (_request, reply) => reply.status(503).send({ error: "unavailable" }));
+
+ await app.inject({ method: "GET", url: "/unavailable" });
+
+ expect(requestEvents(events)).toEqual([
+ expect.objectContaining({
+ level: 50,
+ statusCode: 503,
+ msg: "Request completed with server error",
+ }),
+ ]);
+ });
+
+ it("logs thrown failures once with the serialized error", async () => {
+ const { app, events } = createApp();
+ app.get("/broken", async () => {
+ throw new Error("boom");
+ });
+
+ await app.inject({ method: "GET", url: "/broken" });
+
+ expect(requestEvents(events)).toEqual([
+ expect.objectContaining({
+ level: 50,
+ statusCode: 500,
+ err: expect.objectContaining({ message: "boom" }),
+ msg: "Request failed",
+ }),
+ ]);
+ });
+
+ it("logs thrown client failures at warn", async () => {
+ const { app, events } = createApp();
+ app.get("/invalid", async () => {
+ const error = new Error("invalid") as Error & { statusCode: number };
+ error.statusCode = 400;
+ throw error;
+ });
+
+ await app.inject({ method: "GET", url: "/invalid" });
+
+ expect(requestEvents(events)).toEqual([
+ expect.objectContaining({ level: 40, statusCode: 400, msg: "Request failed" }),
+ ]);
+ });
+
+ it("respects silent route logging", async () => {
+ const { app, events } = createApp();
+ app.get("/health", { logLevel: "silent" }, () => "OK");
+
+ await app.inject({ method: "GET", url: "/health" });
+
+ expect(requestEvents(events)).toEqual([]);
+ });
+});
diff --git a/server/src/lib/logger/requestLogging.ts b/server/src/lib/logger/requestLogging.ts
new file mode 100644
index 000000000..62d0402b4
--- /dev/null
+++ b/server/src/lib/logger/requestLogging.ts
@@ -0,0 +1,80 @@
+import type { FastifyError, FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
+
+const HIGH_VOLUME_SUCCESS_ROUTES = new Set([
+ "/api/identify",
+ "/api/metrics.js",
+ "/api/replay.js",
+ "/api/script.js",
+ "/api/track",
+]);
+
+function requestRoute(request: FastifyRequest): string {
+ return request.routeOptions?.url ?? requestPath(request);
+}
+
+function requestPath(request: FastifyRequest): string {
+ return request.url.split("?", 1)[0];
+}
+
+function isHighVolumeSuccessRoute(route: string): boolean {
+ return HIGH_VOLUME_SUCCESS_ROUTES.has(route) || route.endsWith("/session-replay/record/:siteId");
+}
+
+function responseTimeMs(reply: FastifyReply): number {
+ return Math.round(reply.elapsedTime * 100) / 100;
+}
+
+function requestContext(request: FastifyRequest, reply: FastifyReply, statusCode = reply.statusCode) {
+ return {
+ method: request.method,
+ url: requestPath(request),
+ route: requestRoute(request),
+ statusCode,
+ responseTimeMs: responseTimeMs(reply),
+ };
+}
+
+function errorStatusCode(error: FastifyError, reply: FastifyReply): number {
+ if (typeof error.statusCode === "number") return error.statusCode;
+ if (reply.statusCode >= 400) return reply.statusCode;
+ return 500;
+}
+
+export function registerRequestLogging(fastify: FastifyInstance): void {
+ const requestsWithThrownErrors = new WeakSet<FastifyRequest>();
+
+ fastify.addHook("onError", (request, reply, error, done) => {
+ requestsWithThrownErrors.add(request);
+ const statusCode = errorStatusCode(error, reply);
+ const context = { err: error, ...requestContext(request, reply, statusCode) };
+
+ if (statusCode >= 500) {
+ request.log.error(context, "Request failed");
+ } else {
+ request.log.warn(context, "Request failed");
+ }
+
+ done();
+ });
+
+ fastify.addHook("onResponse", (request, reply, done) => {
+ if (requestsWithThrownErrors.delete(request)) {
+ done();
+ return;
+ }
+
+ const context = requestContext(request, reply);
+
+ if (reply.statusCode >= 500) {
+ request.log.error(context, "Request completed with server error");
+ } else if (reply.statusCode >= 400) {
+ request.log.warn(context, "Request completed with client error");
+ } else if (isHighVolumeSuccessRoute(context.route)) {
+ request.log.debug(context, "Request completed");
+ } else {
+ request.log.info(context, "Request completed");
+ }
+
+ done();
+ });
+}