Skip to content

Commit

Permalink
clean up logging
Browse files Browse the repository at this point in the history
  • Loading branch information
0age committed Dec 12, 2024
1 parent 17ebcf7 commit a610a4d
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 45 deletions.
58 changes: 23 additions & 35 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import './env';
import './types';
import fastify, { FastifyInstance } from 'fastify';
import fastify from 'fastify';
import type { FastifyInstance } from 'fastify';
import env from '@fastify/env';
import fastifyStatic from '@fastify/static';
import * as path from 'path';
Expand All @@ -16,61 +16,51 @@ import cors from '@fastify/cors'; // Import cors plugin

const server = fastify({
logger: {
level: 'error', // Only log errors by default
level: 'info',
transport: {
target: 'pino-pretty',
options: {
translateTime: 'HH:MM:ss Z',
ignore: 'pid,hostname',
ignore: 'pid,hostname,reqId,responseTime,req,res',
colorize: true,
messageFormat: '{msg}',
},
},
},
disableRequestLogging: true,
});

// Only log server start
server.log.info('Server starting up');

// List of API endpoints we want to log
const API_ENDPOINTS = [
'/health',
'/session',
'/compact',
'/compacts',
'/balance',
'/balances',
'/session/',
'/compact/',
'/balance/',
'/suggested-nonce',
];

// Helper to check if a URL is an API endpoint
function isApiEndpoint(url: string): boolean {
return API_ENDPOINTS.some(
(endpoint) => url === endpoint || url.startsWith(`${endpoint}/`)
);
}

server.addHook('onRequest', async (request) => {
if (isApiEndpoint(request.url)) {
request.log.info(
{
method: request.method,
url: request.url,
id: request.id,
},
'API Request'
// Remove query parameters for matching
const path = url.split('?')[0];
// Remove trailing slash for consistency
const normalizedPath = path.endsWith('/') ? path.slice(0, -1) : path;

return API_ENDPOINTS.some((endpoint) => {
// Either exact match or starts with endpoint + '/'
return (
normalizedPath === endpoint || normalizedPath.startsWith(endpoint + '/')
);
}
});
});
}

server.addHook('onResponse', async (request, reply) => {
if (isApiEndpoint(request.url)) {
request.log.info(
{
method: request.method,
url: request.url,
statusCode: reply.statusCode,
id: request.id,
duration: reply.elapsedTime,
},
'API Response'
`${request.method} ${request.url} - ${reply.statusCode} (${reply.elapsedTime.toFixed(1)}ms)`
);
}
});
Expand Down Expand Up @@ -168,12 +158,10 @@ if (isMainModule) {
void (async (): Promise<void> => {
try {
const server = await build();
server.log.level = 'info'; // Temporarily increase log level for startup
await server.listen({
port: parseInt(process.env.PORT || '3000'),
host: '0.0.0.0',
});
server.log.level = 'error'; // Reset back to error-only after startup
} catch (err) {
console.error('Error starting server:', err);
process.exit(1);
Expand Down
12 changes: 6 additions & 6 deletions src/routes/balance.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import { getAddress } from 'viem/utils';
import { getAllocatedBalance } from '../balance';
import {
Expand Down Expand Up @@ -40,11 +40,11 @@ export async function setupBalanceRoutes(
> => {
try {
const sponsor = request.session!.address;
server.log.info(`Processing balances request for sponsor: ${sponsor}`);
server.log.debug(`Processing balances request for sponsor: ${sponsor}`);

// Get all resource locks for the sponsor
const response = await getAllResourceLocks(sponsor);
server.log.info(
server.log.debug(
`Found ${response?.account?.resourceLocks?.items?.length || 0} resource locks`
);

Expand Down Expand Up @@ -92,7 +92,7 @@ export async function setupBalanceRoutes(
(sum, delta) => sum + BigInt(delta.delta),
BigInt(0)
);
server.log.info(
server.log.debug(
{
chainId: lock.chainId,
lockId: lock.resourceLock.lockId,
Expand All @@ -113,7 +113,7 @@ export async function setupBalanceRoutes(
// This is our allocatable balance (only includes finalized amounts)
const allocatableBalance = finalizedBalance;

server.log.info(
server.log.debug(
{
chainId: lock.chainId,
lockId: lock.resourceLock.lockId,
Expand All @@ -140,7 +140,7 @@ export async function setupBalanceRoutes(
lockIdBigInt,
lockDetails.account.claims.items.map((claim) => claim.claimHash)
);
server.log.info(
server.log.debug(
{
chainId: lock.chainId,
lockId: lock.resourceLock.lockId,
Expand Down
8 changes: 5 additions & 3 deletions src/routes/health.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { FastifyInstance } from 'fastify';
import type { FastifyInstance } from 'fastify';
import { getCachedSupportedChains } from '../graphql';

interface HealthResponse {
Expand All @@ -17,7 +17,7 @@ export async function setupHealthRoutes(
server: FastifyInstance
): Promise<void> {
// Health check endpoint
server.get('/health', async (): Promise<HealthResponse> => {
server.get('/health', async (_request): Promise<HealthResponse> => {
if (!process.env.ALLOCATOR_ADDRESS || !process.env.SIGNING_ADDRESS) {
throw new Error('Required environment variables are not set');
}
Expand All @@ -27,12 +27,14 @@ export async function setupHealthRoutes(
throw new Error('Supported chains data not initialized');
}

return {
const response = {
status: 'healthy',
allocatorAddress: process.env.ALLOCATOR_ADDRESS,
signingAddress: process.env.SIGNING_ADDRESS,
timestamp: new Date().toISOString(),
supportedChains,
};

return response;
});
}
2 changes: 1 addition & 1 deletion src/session.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { FastifyInstance } from 'fastify';
import type { FastifyInstance } from 'fastify';
import { getAddress, verifyMessage } from 'viem/utils';
import { hexToBytes } from 'viem/utils';
import { randomUUID } from 'crypto';
Expand Down

0 comments on commit a610a4d

Please sign in to comment.