From a610a4d6e2677a516d369daea94dd9fa0071ab1c Mon Sep 17 00:00:00 2001 From: 0age <37939117+0age@users.noreply.github.com> Date: Thu, 12 Dec 2024 08:56:43 -0800 Subject: [PATCH] clean up logging --- src/index.ts | 58 +++++++++++++++++-------------------------- src/routes/balance.ts | 12 ++++----- src/routes/health.ts | 8 +++--- src/session.ts | 2 +- 4 files changed, 35 insertions(+), 45 deletions(-) diff --git a/src/index.ts b/src/index.ts index eb13443..9fda145 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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'; @@ -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)` ); } }); @@ -168,12 +158,10 @@ if (isMainModule) { void (async (): Promise => { 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); diff --git a/src/routes/balance.ts b/src/routes/balance.ts index ee72b81..5ce9d79 100644 --- a/src/routes/balance.ts +++ b/src/routes/balance.ts @@ -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 { @@ -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` ); @@ -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, @@ -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, @@ -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, diff --git a/src/routes/health.ts b/src/routes/health.ts index 402dcdc..5e910dc 100644 --- a/src/routes/health.ts +++ b/src/routes/health.ts @@ -1,4 +1,4 @@ -import { FastifyInstance } from 'fastify'; +import type { FastifyInstance } from 'fastify'; import { getCachedSupportedChains } from '../graphql'; interface HealthResponse { @@ -17,7 +17,7 @@ export async function setupHealthRoutes( server: FastifyInstance ): Promise { // Health check endpoint - server.get('/health', async (): Promise => { + server.get('/health', async (_request): Promise => { if (!process.env.ALLOCATOR_ADDRESS || !process.env.SIGNING_ADDRESS) { throw new Error('Required environment variables are not set'); } @@ -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; }); } diff --git a/src/session.ts b/src/session.ts index 271bba4..8f63bc1 100644 --- a/src/session.ts +++ b/src/session.ts @@ -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';