Skip to content

Full Toolkit for Next-Level Domain Analysis

Add evlog structured logging integration 📋🪵 (#65)

Felix Wotschofsky5603d50492f3
diff --git a/.eslintrc.json b/.eslintrc.json
index 1775388..cacb013 100644
--- a/.eslintrc.json
+++ b/.eslintrc.json
@@ -2,12 +2,7 @@
"extends": "next/core-web-vitals",
"plugins": ["@typescript-eslint", "eslint-plugin-react-compiler"],
"rules": {
- "no-console": [
- "error",
- {
- "allow": ["error", "info", "warn"]
- }
- ],
+ "no-console": "error",
"@typescript-eslint/consistent-type-imports": "error",
"react-compiler/react-compiler": "error"
}
diff --git a/app/api/ip-details/route.ts b/app/api/ip-details/route.ts
index a7826d1..6e36e19 100644
--- a/app/api/ip-details/route.ts
+++ b/app/api/ip-details/route.ts
@@ -1,6 +1,7 @@
import { NextResponse } from 'next/server';
import isIP from 'validator/lib/isIP';
+import { useLogger, withEvlog } from '@/lib/evlog';
import { getIpDetails, lookupReverse } from '@/lib/ips';
export type IpLookupResponse = Pick<
@@ -10,11 +11,13 @@ export type IpLookupResponse = Pick<
reverse: string[];
};
-export async function GET(request: Request) {
+export const GET = withEvlog(async (request: Request) => {
+ const log = useLogger();
const { searchParams } = new URL(request.url);
const ip = searchParams.get('ip');
if (!ip || !isIP(ip)) {
+ log.set({ status: 400, reason: 'invalid_ip', hasIp: Boolean(ip) });
return NextResponse.json(
{
error: true,
@@ -34,6 +37,13 @@ export async function GET(request: Request) {
lookupReverse(ip),
]);
+ log.set({
+ ip,
+ reverseCount: reverse.length,
+ country: data.country,
+ region: data.regionName,
+ });
+
return NextResponse.json(
{
reverse: reverse,
@@ -54,4 +64,4 @@ export async function GET(request: Request) {
},
},
);
-}
+});
diff --git a/app/api/search-suggestions/route.ts b/app/api/search-suggestions/route.ts
index 560db5e..f003389 100644
--- a/app/api/search-suggestions/route.ts
+++ b/app/api/search-suggestions/route.ts
@@ -1,5 +1,6 @@
import { NextResponse } from 'next/server';
+import { useLogger, withEvlog } from '@/lib/evlog';
import { getSearchSuggestions } from '@/lib/search';
import { normalizeDomain } from '@/lib/search-parser';
@@ -7,29 +8,36 @@ export const preferredRegion = 'home';
const VALID_QUERY_REGEX = /^[a-z0-9-_.]+$/i;
-export const GET = async (request: Request) => {
+export const GET = withEvlog(async (request: Request) => {
+ const log = useLogger();
const { searchParams } = new URL(request.url);
const query = searchParams.get('q');
if (!query) {
+ log.set({ status: 400, reason: 'missing_query' });
return new Response('Missing query', {
status: 400,
});
}
if (query !== normalizeDomain(query)) {
+ log.set({ status: 400, reason: 'not_normalized' });
return new Response('Query is not normalized', {
status: 400,
});
}
+ log.set({ query });
+
const suggestions = VALID_QUERY_REGEX.test(query)
? await getSearchSuggestions(query)
: [];
+ log.set({ suggestionCount: suggestions.length });
+
return NextResponse.json(suggestions, {
headers: {
'Cache-Control': 'public, s-maxage=21600',
},
});
-};
+});
diff --git a/app/api/stargazers-summary/route.ts b/app/api/stargazers-summary/route.ts
index ac16b1b..9a55982 100644
--- a/app/api/stargazers-summary/route.ts
+++ b/app/api/stargazers-summary/route.ts
@@ -1,25 +1,31 @@
import { NextResponse } from 'next/server';
+import { useLogger, withEvlog } from '@/lib/evlog';
import { getStargazersSummary } from '@/lib/github';
-export const GET = async () => {
+export const GET = withEvlog(async () => {
+ const log = useLogger();
+
try {
const stargazers = await getStargazersSummary(
'wotschofsky',
'domain-digger',
);
+ log.set({ stargazerCount: stargazers.recentStargazers.length });
+
return NextResponse.json(stargazers, {
headers: {
'Cache-Control': 'public, s-maxage=3600',
},
});
} catch (error) {
- console.error('Failed to fetch recent stargazers:', error);
+ log.set({ event: 'stargazers_summary_failed' });
+ log.error(error instanceof Error ? error : new Error(String(error)));
return NextResponse.json(
{ error: 'Failed to fetch recent stargazers' },
{ status: 500 },
);
}
-};
+});
diff --git a/app/api/user-ip/route.ts b/app/api/user-ip/route.ts
index 08f23fd..bff8059 100644
--- a/app/api/user-ip/route.ts
+++ b/app/api/user-ip/route.ts
@@ -1,9 +1,12 @@
import { type NextRequest, NextResponse } from 'next/server';
import { getVisitorIp } from '@/lib/api';
+import { useLogger, withEvlog } from '@/lib/evlog';
-export const GET = async (request: NextRequest) => {
+export const GET = withEvlog(async (request: NextRequest) => {
+ const log = useLogger();
const ip = getVisitorIp(request.headers);
+ log.set({ ip });
return NextResponse.json({ ip });
-};
+});
diff --git a/app/api/whois-summary/route.ts b/app/api/whois-summary/route.ts
index 42e2c92..0bbb7a8 100644
--- a/app/api/whois-summary/route.ts
+++ b/app/api/whois-summary/route.ts
@@ -1,15 +1,18 @@
import { NextResponse } from 'next/server';
+import { useLogger, withEvlog } from '@/lib/evlog';
import { getWhoisSummary } from '@/lib/whois';
export type WhoisSummaryResponse = Awaited<ReturnType<typeof getWhoisSummary>>;
export type WhoisSummaryErrorResponse = { error: true; message: string };
-export async function GET(request: Request) {
+export const GET = withEvlog(async (request: Request) => {
+ const log = useLogger();
const { searchParams } = new URL(request.url);
const domain = searchParams.get('domain');
if (!domain) {
+ log.set({ status: 400, reason: 'missing_domain' });
return NextResponse.json(
{ error: true, message: 'No domain provided' },
{
@@ -21,6 +24,8 @@ export async function GET(request: Request) {
);
}
+ log.set({ domain });
+
try {
const summary = await getWhoisSummary(domain);
return NextResponse.json(summary, {
@@ -29,7 +34,8 @@ export async function GET(request: Request) {
},
});
} catch (error) {
- console.error(error);
+ log.set({ event: 'whois_summary_failed' });
+ log.error(error instanceof Error ? error : new Error(String(error)));
return NextResponse.json(
{ error: true, message: 'Error fetching whois summary' },
@@ -41,4 +47,4 @@ export async function GET(request: Request) {
},
);
}
-}
+});
diff --git a/app/lookup/[domain]/map/page.tsx b/app/lookup/[domain]/map/page.tsx
index 19ab689..47ff1c9 100644
--- a/app/lookup/[domain]/map/page.tsx
+++ b/app/lookup/[domain]/map/page.tsx
@@ -1,3 +1,4 @@
+import { log } from 'evlog';
import { CheckCircleIcon, InfoIcon, ShieldAlertIcon } from 'lucide-react';
import type { Metadata } from 'next';
import { headers } from 'next/headers';
@@ -40,7 +41,7 @@ const MapResultsPage: FC<MapResultsPageProps> = async ({ params }) => {
const { isBot, userAgent } = isUserBot(headersList);
if (isBot) {
- console.info('Bot detected, blocking request, UA:', userAgent);
+ log.info({ message: 'bot_blocked', userAgent, domain });
return (
<IconAlert
className="mx-auto mt-24"
diff --git a/app/providers.tsx b/app/providers.tsx
index 3e494d7..6100e75 100644
--- a/app/providers.tsx
+++ b/app/providers.tsx
@@ -1,5 +1,6 @@
'use client';
+import { EvlogProvider } from 'evlog/next/client';
import PlausibleProvider from 'next-plausible';
import { ThemeProvider } from 'next-themes';
import { type FC, type ReactNode } from 'react';
@@ -41,9 +42,11 @@ type ProvidersProps = {
};
export const Providers: FC<ProvidersProps> = ({ children }) => (
- <ThemeProvider attribute="class">
- <SWRConfig value={{ fetcher: swrFetcher }}>
- <CustomizedPlausibleProvider>{children}</CustomizedPlausibleProvider>
- </SWRConfig>
- </ThemeProvider>
+ <EvlogProvider service="domain-digger">
+ <ThemeProvider attribute="class">
+ <SWRConfig value={{ fetcher: swrFetcher }}>
+ <CustomizedPlausibleProvider>{children}</CustomizedPlausibleProvider>
+ </SWRConfig>
+ </ThemeProvider>
+ </EvlogProvider>
);
diff --git a/components/boundary-error.tsx b/components/boundary-error.tsx
index d6caf01..8142e6b 100644
--- a/components/boundary-error.tsx
+++ b/components/boundary-error.tsx
@@ -1,5 +1,6 @@
'use client';
+import { log } from 'evlog/next/client';
import { type FC, useEffect, useState } from 'react';
import { Button } from '@/components/ui/button';
@@ -21,7 +22,13 @@ export const BoundaryError: FC<BoundaryErrorProps> = ({
const [isPending, setIsPending] = useState(false);
useEffect(() => {
- console.error(error);
+ log.error({
+ message: 'boundary_error',
+ name: error.name,
+ error: error.message,
+ digest: error.digest,
+ stack: error.stack,
+ });
}, [error]);
const userFacing = parseUserFacingDigest(error.digest);
diff --git a/eslint.config.mjs b/eslint.config.mjs
index 9b6050b..d032753 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -10,7 +10,7 @@ export default [
'react-compiler': reactCompiler,
},
rules: {
- 'no-console': ['error', { allow: ['error', 'info', 'warn'] }],
+ 'no-console': 'error',
'@typescript-eslint/consistent-type-imports': 'error',
'react-compiler/react-compiler': 'error',
diff --git a/instrumentation.ts b/instrumentation.ts
new file mode 100644
index 0000000..d073fb1
--- /dev/null
+++ b/instrumentation.ts
@@ -0,0 +1,5 @@
+import { defineNodeInstrumentation } from 'evlog/next/instrumentation';
+
+export const { register, onRequestError } = defineNodeInstrumentation(
+ () => import('./lib/evlog'),
+);
diff --git a/lib/analytics.ts b/lib/analytics.ts
index ec6ce15..86878c7 100644
--- a/lib/analytics.ts
+++ b/lib/analytics.ts
@@ -1,3 +1,4 @@
+import { log } from 'evlog/next/client';
import { usePlausible } from 'next-plausible';
type EmptyEvent = Record<string, never>;
@@ -21,7 +22,7 @@ export const useAnalytics = () => {
const plausible = usePlausible();
const reportEvent = <T extends keyof Events>(event: T, props: Events[T]) => {
- console.info('Reporting event', { event, props });
+ log.info({ message: 'analytics_event', event, props });
plausible(event, { props });
};
diff --git a/lib/evlog.ts b/lib/evlog.ts
new file mode 100644
index 0000000..38879d7
--- /dev/null
+++ b/lib/evlog.ts
@@ -0,0 +1,14 @@
+import { createEvlog } from 'evlog/next';
+import { createInstrumentation } from 'evlog/next/instrumentation';
+
+import { env } from '@/env';
+
+export const { withEvlog, useLogger, log, createError } = createEvlog({
+ service: 'domain-digger',
+ env: { environment: env.NODE_ENV },
+});
+
+export const { register, onRequestError } = createInstrumentation({
+ service: 'domain-digger',
+ env: { environment: env.NODE_ENV },
+});
diff --git a/lib/github.ts b/lib/github.ts
index f3b9db6..9d7aa1a 100644
--- a/lib/github.ts
+++ b/lib/github.ts
@@ -1,3 +1,5 @@
+import { log } from 'evlog';
+
import { env } from '@/env';
type SponsorsQueryResponse = {
@@ -23,7 +25,7 @@ type SponsorsQueryResponse = {
export const getGitHubSponsors = async (username: string) => {
if (!env.GITHUB_TOKEN) {
- console.warn('GITHUB_TOKEN not set; skipping GitHub sponsors');
+ log.warn({ message: 'github_token_missing', context: 'sponsors' });
return [];
}
@@ -118,7 +120,7 @@ export const getStargazersSummary = async (
limit = 5,
): Promise<StargazerSummary> => {
if (!env.GITHUB_TOKEN) {
- console.warn('GITHUB_TOKEN not set; skipping GitHub stargazers');
+ log.warn({ message: 'github_token_missing', context: 'stargazers' });
return {
recentStargazers: Array.from({ length: limit }).map(() => ({
name: 'GitHub User',
diff --git a/lib/search.ts b/lib/search.ts
index ecd40f1..14014c3 100644
--- a/lib/search.ts
+++ b/lib/search.ts
@@ -1,3 +1,4 @@
+import { log } from 'evlog';
import { headers } from 'next/headers';
import { after } from 'next/server';
@@ -44,10 +45,10 @@ export const recordLookup = async (payload: LookupLogPayload) => {
.catch((error) => {
if ('errors' in error) {
for (const err of error.errors) {
- console.error(err);
+ log.error({ message: 'bigquery_insert_failed', error: err });
}
} else {
- console.error(error);
+ log.error({ message: 'bigquery_insert_failed', error });
}
});
};
diff --git a/lib/subdomains.ts b/lib/subdomains.ts
index 3825994..2fb2e03 100644
--- a/lib/subdomains.ts
+++ b/lib/subdomains.ts
@@ -32,7 +32,6 @@ const readDiscovery = (line: string) => {
const record = subfinderRecordSchema.safeParse(JSON.parse(line));
return record.success ? record.data : null;
} catch {
- console.error('Failed to parse subfinder record:', line);
return null;
}
};
diff --git a/lib/utils.test.ts b/lib/utils.test.ts
index 1689374..d4d7179 100644
--- a/lib/utils.test.ts
+++ b/lib/utils.test.ts
@@ -1,3 +1,4 @@
+import { log } from 'evlog';
import {
afterEach,
beforeEach,
@@ -44,7 +45,7 @@ describe('retry', () => {
let warnSpy: MockInstance;
beforeEach(() => {
- warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ warnSpy = vi.spyOn(log, 'warn').mockImplementation(() => {});
});
afterEach(() => {
@@ -70,7 +71,10 @@ describe('retry', () => {
expect(result).toBe('success');
expect(mockFn).toHaveBeenCalledTimes(3);
expect(warnSpy).toHaveBeenCalledTimes(2);
- expect(warnSpy).toHaveBeenCalledWith(error.message.toString());
+ expect(warnSpy).toHaveBeenCalledWith({
+ message: 'retrying_after_error',
+ error: error.message,
+ });
});
it('should throw the last error after exhausting all retries', async () => {
diff --git a/lib/utils.ts b/lib/utils.ts
index bc0ec16..aa06a81 100644
--- a/lib/utils.ts
+++ b/lib/utils.ts
@@ -1,4 +1,5 @@
import { type ClassValue, clsx } from 'clsx';
+import { log } from 'evlog';
import { twMerge } from 'tailwind-merge';
import { getDomain, parse as tldtsParse } from 'tldts';
@@ -20,7 +21,10 @@ export const retry = <T extends Function>(fn: T, maxRetries: number) =>
if (maxRetries <= 0) {
throw err;
}
- console.warn(err.message?.toString());
+ log.warn({
+ message: 'retrying_after_error',
+ error: err.message?.toString(),
+ });
return retry(fn, maxRetries - 1);
});
@@ -28,7 +32,11 @@ export const retry = <T extends Function>(fn: T, maxRetries: number) =>
export const isValidDomain = (domain: string) => {
if (typeof domain !== 'string') {
if (process?.env.VITEST !== 'true') {
- console.warn('isValidDomain expects a string input, received', domain);
+ log.warn({
+ message: 'invalid_domain_input_type',
+ receivedType: typeof domain,
+ received: domain,
+ });
}
return false;
}
diff --git a/package.json b/package.json
index 9cb5b32..f25263d 100644
--- a/package.json
+++ b/package.json
@@ -36,6 +36,7 @@
"clsx": "^2.1.1",
"dataloader": "^2.2.3",
"dns-packet": "^5.6.1",
+ "evlog": "^2.18.1",
"execa": "^9.6.1",
"hyperscript": "^2.0.2",
"isbot": "^5.1.37",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a1f1e47..e92d19c 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -72,6 +72,9 @@ importers:
dns-packet:
specifier: ^5.6.1
version: 5.6.1
+ evlog:
+ specifier: ^2.18.1
execa:
specifier: ^9.6.1
version: 9.6.1
@@ -2986,6 +2989,62 @@ packages:
resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==}
engines: {node: '>=0.10.0'}
+ resolution: {integrity: sha512-uP7NNcmgQST0VdJ5c+gm4uBOOQDc/lGDWwH6aRS2H4C6mu4Hm7N8bCi6cSKIz8+If6pD2uA5EgPuhvI7OH+SHA==}
+ peerDependencies:
+ '@nestjs/common': '>=11.1.19'
+ '@nuxt/kit': ^4.4.2
+ '@orpc/server': '>=1.14.0'
+ '@tanstack/start-client-core': ^1.167.20
+ ai: '>=6.0.168'
+ elysia: '>=1.4.28'
+ express: '>=5.2.1'
+ fastify: '>=5.8.5'
+ h3: ^1.15.11
+ hono: '>=4.11.0'
+ next: '>=16.2.4'
+ nitro: ^3.0.260311-beta
+ nitropack: ^2.13.3
+ ofetch: ^1.5.1
+ react: '>=19.2.5'
+ react-router: '>=7.14.2'
+ vite: ^7.0.0 || ^8.0.0
+ peerDependenciesMeta:
+ '@nestjs/common':
+ optional: true
+ '@nuxt/kit':
+ optional: true
+ '@orpc/server':
+ optional: true
+ '@tanstack/start-client-core':
+ optional: true
+ ai:
+ optional: true
+ elysia:
+ optional: true
+ express:
+ optional: true
+ fastify:
+ optional: true
+ h3:
+ optional: true
+ hono:
+ optional: true
+ next:
+ optional: true
+ nitro:
+ optional: true
+ nitropack:
+ optional: true
+ ofetch:
+ optional: true
+ react:
+ optional: true
+ react-router:
+ optional: true
+ vite:
+ optional: true
+
resolution: {integrity: sha512-9Be3ZoN4LmYR90tUoVu2te2BsbzHfhJyfEiAVfz7N5/zv+jduIfLrV2xdQXOHbaD6KgpGdO9PRPM1Y4Q9QkPkA==}
engines: {node: ^18.19.0 || >=20.5.0}
@@ -7399,6 +7458,12 @@ snapshots:
+ optionalDependencies:
+ react: 19.2.4
+
dependencies:
'@sindresorhus/merge-streams': 4.0.0
diff --git a/proxy.ts b/proxy.ts
index 505840e..30b6ca9 100644
--- a/proxy.ts
+++ b/proxy.ts
@@ -1,8 +1,15 @@
-import { NextRequest, NextResponse } from 'next/server';
+import { evlogMiddleware } from 'evlog/next';
+import { type NextRequest, NextResponse } from 'next/server';
import { parseSearchInput } from './lib/search-parser';
-export function proxy(request: NextRequest) {
+const withEvlogHeaders = evlogMiddleware();
+
+export async function proxy(request: NextRequest) {
+ if (request.nextUrl.pathname !== '/') {
+ return withEvlogHeaders(request);
+ }
+
const url = request.nextUrl.clone();
const searchTerm = url.searchParams.get('q')!;
const parsed = parseSearchInput(searchTerm);
@@ -26,6 +33,7 @@ export function proxy(request: NextRequest) {
export const config = {
matcher: [
+ '/api/:path*',
{
source: '/',
has: [{ type: 'query', key: 'q' }],