Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Refactor logging #1170

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion web/.env.test
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ SENDGRID_TEAM_INVITE_TEMPLATE_ID=temporary_test_id

# Datadog
NEXT_SERVER_DD_API_KEY=
NEXT_SERVER_DD_SERVICE_NAME=developer-portal
NEXT_SERVER_DD_SERVICE_NAME=worldcoin-developer-portal


# Auth0
Expand Down
2 changes: 1 addition & 1 deletion web/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ WORKDIR /app
RUN npm install -g [email protected] && corepack --version

# TODO: Can be further optimized to remove next peer dependency
RUN corepack enable pnpm && pnpm i [email protected] [email protected] dd-trace@5.12.0
RUN corepack enable pnpm && pnpm i [email protected] [email protected] dd-trace@5.35.0

# Rebuild the source code only when needed
FROM base AS builder
Expand Down
18 changes: 17 additions & 1 deletion web/api/helpers/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,24 @@ export function errorResponse(params: {
detail?: string;
attribute?: string | null;
req: NextRequest;
skipLogging?: boolean;
}) {
const {
statusCode,
code,
detail = "Something went wrong",
attribute = null,
req,
skipLogging = false,
} = params;

if (skipLogging) {
return NextResponse.json(
{ code, detail, attribute },
{ status: statusCode },
);
}

if (statusCode >= 500) {
logger.error(detail, { req, error: { statusCode, code, attribute } });
} else {
Expand Down Expand Up @@ -89,7 +98,14 @@ export function errorValidation(
attribute: string | null,
req: NextRequest,
) {
return errorResponse({ statusCode: 400, code, detail, attribute, req });
return errorResponse({
statusCode: 400,
code,
detail,
attribute,
req,
skipLogging: true,
});
}

export function errorOIDCResponse(
Expand Down
2 changes: 2 additions & 0 deletions web/api/v2/minikit/app-metadata/[app_id]/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ export const GET = async (
detail: "API key not found.",
attribute: "api_key",
req,
skipLogging: true,
});
}

Expand All @@ -61,6 +62,7 @@ export const GET = async (
detail: "API key is inactive.",
attribute: "api_key",
req,
skipLogging: true,
});
}

Expand Down
5 changes: 3 additions & 2 deletions web/api/v2/public/apps/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
import { getSdk as getWebHighlightsSdk } from "./graphql/get-app-web-highlights.generated";

import { formatAppMetadata, rankApps } from "@/api/helpers/app-store";
import { logger } from "@/lib/logger";
import {
GetHighlightsQuery,
getSdk as getHighlightsSdk,
Expand Down Expand Up @@ -83,7 +84,7 @@ export const GET = async (request: NextRequest) => {
const { app_rankings } = await getWebHighlightsSdk(client).GetHighlights();
highlightsIds = app_rankings[0]?.rankings ?? [];
} catch (error) {
console.log(error);
logger.error("Error fetching highlights", { error, req: request });
return errorResponse({
statusCode: 500,
code: "server_error",
Expand Down Expand Up @@ -115,7 +116,7 @@ export const GET = async (request: NextRequest) => {
});
highlightsApps = highlights;
} catch (error) {
console.log(error);
logger.error("Error fetching app rankings", { error, req: request });
return errorResponse({
statusCode: 500,
code: "server_error",
Expand Down
5 changes: 4 additions & 1 deletion web/api/v2/verify/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ export async function POST(
detail: "This action does not have a valid external nullifier set.",
attribute: null,
req,
skipLogging: true,
});
}

Expand Down Expand Up @@ -173,16 +174,17 @@ export async function POST(
detail: error?.message || "There was an error verifying this proof.",
attribute: error?.attribute || null,
req,
skipLogging: true,
});
}
} catch (e: any) {
console.warn("Error verifying proof", { error: e });
return errorResponse({
statusCode: 400,
code: "verification_error",
detail: e.message,
attribute: null,
req,
skipLogging: true,
});
}

Expand Down Expand Up @@ -244,6 +246,7 @@ export async function POST(
: e.message,
attribute: null,
req,
skipLogging: true,
});
}
}
2 changes: 1 addition & 1 deletion web/legacy/backend/errors.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { logger } from "@/legacy/lib/logger";
import { logger } from "@/lib/logger";
import { NextApiRequest, NextApiResponse } from "next";

export function errorResponse(
Expand Down
6 changes: 3 additions & 3 deletions web/legacy/backend/jwks.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { JWK_TIME_TO_LIVE, JWK_TTL_USABLE } from "@/legacy/lib/constants";
import { JWKModel } from "@/legacy/lib/models";
import { logger } from "@/lib/logger";
import { gql } from "@apollo/client";
import { createPublicKey } from "crypto";
import dayjs from "dayjs";
import { JWKModel } from "@/legacy/lib/models";
import { getAPIServiceClient } from "./graphql";
import { createKMSKey, getKMSClient, scheduleKeyDeletion } from "./kms";
import { JWK_TIME_TO_LIVE, JWK_TTL_USABLE } from "@/legacy/lib/constants";
import { logger } from "@/legacy/lib/logger";

export type CreateJWKResult = {
keyId: string;
Expand Down
2 changes: 1 addition & 1 deletion web/legacy/backend/kms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
* Contains all functions for interacting with Amazon KMS
*/

import { logger } from "@/lib/logger";
import {
CreateKeyCommand,
DescribeKeyCommand,
Expand All @@ -13,7 +14,6 @@ import {
} from "@aws-sdk/client-kms";
import { base64url } from "jose";
import { retrieveJWK } from "./jwks";
import { logger } from "@/legacy/lib/logger";

export type CreateKeyResult =
| {
Expand Down
2 changes: 1 addition & 1 deletion web/legacy/backend/oidc.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { logger } from "@/legacy/lib/logger";
import { ActionModel, AppModel, RedirectModel } from "@/legacy/lib/models";
import { logger } from "@/lib/logger";
import { IInternalError, OIDCFlowType, OIDCResponseType } from "@/lib/types";
import { gql } from "@apollo/client";
import { VerificationLevel } from "@worldcoin/idkit-core";
Expand Down
2 changes: 1 addition & 1 deletion web/legacy/backend/verify.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { validateABILikeEncoding } from "@/legacy/lib/hashing";
import { logger } from "@/legacy/lib/logger";
import { IInternalError } from "@/legacy/lib/types";
import { logger } from "@/lib/logger";
import { sequencerMapping } from "@/lib/utils";
import { ApolloClient, NormalizedCacheObject, gql } from "@apollo/client";
import { VerificationLevel } from "@worldcoin/idkit-core";
Expand Down
143 changes: 0 additions & 143 deletions web/legacy/lib/logger.ts

This file was deleted.

27 changes: 21 additions & 6 deletions web/lib/logger.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { IncomingMessage } from "http";
import { NextApiRequest } from "next";
import { NextRequest } from "next/server";
import winston from "winston";

const apiKey = process.env.NEXT_SERVER_DD_API_KEY;
Expand Down Expand Up @@ -58,18 +59,32 @@ const _logger = winston.createLogger({
});

// NOTE: this is wrapper and formatter for debug request data (this is workaround, because winston don't support async formatters)
async function requestFormatter(req: NextApiRequest | IncomingMessage) {
async function requestFormatter(
req: NextApiRequest | IncomingMessage | NextRequest,
) {
if (!req) {
return {};
}

const ip =
req.socket?.remoteAddress ||
req.headers["x-forwarded-for"] ||
"IP not available";
let ip: string | string[] | undefined;
if (req instanceof NextRequest) {
ip = req.ip;
} else {
ip =
req.socket?.remoteAddress ||
req.headers["x-forwarded-for"] ||
"IP not available";
}

const url = req.url?.replace(/\?.*$/, "");
const method = req.method;
const userAgent = req.headers["user-agent"];
let userAgent: string | undefined;

if (req instanceof NextRequest) {
userAgent = req.headers.get("user-agent") ?? undefined;
} else {
userAgent = req.headers["user-agent"] ?? undefined;
}

const query = req.url?.includes("?")
? Object.fromEntries(
Expand Down
6 changes: 3 additions & 3 deletions web/pages/api/_delete-expired-auth-codes.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { gql } from "@apollo/client";
import { errorNotAllowed } from "@/legacy/backend/errors";
import { getAPIServiceClient } from "@/legacy/backend/graphql";
import { protectInternalEndpoint } from "@/legacy/backend/utils";
import { logger } from "@/lib/logger";
import { gql } from "@apollo/client";
import { NextApiRequest, NextApiResponse } from "next";
import { errorNotAllowed } from "@/legacy/backend/errors";
import { logger } from "@/legacy/lib/logger";

/**
* Deletes expired auth codes
Expand Down
Loading
Loading