Skip to content

Use nest's logger instead of console.log #44

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

Merged
merged 1 commit into from
May 6, 2025
Merged
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
9 changes: 6 additions & 3 deletions src/api/admin/admin.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
HttpStatus,
NotFoundException,
BadRequestException,
Logger,
} from '@nestjs/common';

import { PrismaPromise } from '@prisma/client';
Expand All @@ -21,6 +22,8 @@ import { WinningUpdateRequestDto } from './dto/winnings.dto';
*/
@Injectable()
export class AdminService {
private readonly logger = new Logger(AdminService.name);

/**
* Constructs the admin winning service with the given dependencies.
* @param prisma the prisma service.
Expand Down Expand Up @@ -279,7 +282,7 @@ export class AdminService {
) {
throw error;
}
console.error('Updating winnings failed', error);
this.logger.error('Updating winnings failed', error);
const message = 'Updating winnings failed. ' + error;
result.error = {
code: HttpStatus.INTERNAL_SERVER_ERROR,
Expand Down Expand Up @@ -477,7 +480,7 @@ export class AdminService {
createdAt: item.created_at,
}));
} catch (error) {
console.error('Getting winnings audit failed', error);
this.logger.error('Getting winnings audit failed', error);
const message = 'Searching winnings failed. ' + error;
result.error = {
code: HttpStatus.INTERNAL_SERVER_ERROR,
Expand Down Expand Up @@ -536,7 +539,7 @@ export class AdminService {
externalTransactionDetails: {},
}));
} catch (error) {
console.error('Getting winnings audit failed', error);
this.logger.error('Getting winnings audit failed', error);
const message = 'Searching winnings failed. ' + error;
result.error = {
code: HttpStatus.INTERNAL_SERVER_ERROR,
Expand Down
12 changes: 10 additions & 2 deletions src/api/health-check/healthCheck.controller.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import { Controller, Get, Version, VERSION_NEUTRAL } from '@nestjs/common';
import {
Controller,
Get,
Logger,
Version,
VERSION_NEUTRAL,
} from '@nestjs/common';
import { ApiOperation, ApiProperty, ApiTags } from '@nestjs/swagger';
import { Public } from 'src/core/auth/decorators';
import { PrismaService } from 'src/shared/global/prisma.service';
Expand Down Expand Up @@ -26,6 +32,8 @@ export class GetHealthCheckResponseDto {
@ApiTags('Healthcheck')
@Controller()
export class HealthCheckController {
private readonly logger = new Logger(HealthCheckController.name);

constructor(private readonly prisma: PrismaService) {}

@Public()
Expand All @@ -45,7 +53,7 @@ export class HealthCheckController {
response.status = HealthCheckStatus.healthy;
response.database = 'connected';
} catch (error) {
console.error('Health check failed', error);
this.logger.error('Health check failed', error);
response.status = HealthCheckStatus.unhealthy;
}

Expand Down
6 changes: 4 additions & 2 deletions src/api/repository/winnings.repo.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { HttpStatus, Injectable } from '@nestjs/common';
import { HttpStatus, Injectable, Logger } from '@nestjs/common';
import {
payment_status,
Prisma,
Expand All @@ -20,6 +20,8 @@ const ONE_DAY = 24 * 60 * 60 * 1000;

@Injectable()
export class WinningsRepository {
private readonly logger = new Logger(WinningsRepository.name);

constructor(private readonly prisma: PrismaService) {}

private generateFilterDate(date: DateFilterType) {
Expand Down Expand Up @@ -243,7 +245,7 @@ export class WinningsRepository {
};
// response.data = winnings as any
} catch (error) {
console.error('Searching winnings failed', error);
this.logger.error('Searching winnings failed', error);
const message = 'Searching winnings failed. ' + error;
result.error = {
code: HttpStatus.INTERNAL_SERVER_ERROR,
Expand Down
10 changes: 6 additions & 4 deletions src/api/wallet/wallet.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Injectable, HttpStatus } from '@nestjs/common';
import { Injectable, HttpStatus, Logger } from '@nestjs/common';

import { PrismaService } from 'src/shared/global/prisma.service';

Expand All @@ -13,6 +13,8 @@ import { PaymentMethodRepository } from '../repository/paymentMethod.repo';
*/
@Injectable()
export class WalletService {
private readonly logger = new Logger(WalletService.name);

/**
* Constructs the admin winning service with the given dependencies.
* @param prisma the prisma service.
Expand Down Expand Up @@ -60,16 +62,16 @@ export class WalletService {
],
},
withdrawalMethod: {
isSetupComplete: hasVerifiedPaymentMethod,
isSetupComplete: Boolean(hasVerifiedPaymentMethod),
},
taxForm: {
isSetupComplete: hasActiveTaxForm,
isSetupComplete: Boolean(hasActiveTaxForm),
},
};

result.data = winningTotals;
} catch (error) {
console.error('Getting winnings audit failed', error);
this.logger.error('Getting winnings audit failed', error);
const message = 'Searching winnings failed. ' + error;
result.error = {
code: HttpStatus.INTERNAL_SERVER_ERROR,
Expand Down
10 changes: 6 additions & 4 deletions src/api/webhooks/trolley/handlers/recipient-account.handler.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Injectable } from '@nestjs/common';
import { Injectable, Logger } from '@nestjs/common';
import { WebhookEvent } from '../../webhooks.decorators';
import { PrismaService } from 'src/shared/global/prisma.service';
import {
Expand All @@ -11,6 +11,8 @@ import { PaymentsService } from 'src/shared/payments';

@Injectable()
export class RecipientAccountHandler {
private readonly logger = new Logger(RecipientAccountHandler.name);

constructor(
private readonly prisma: PrismaService,
private readonly paymentsService: PaymentsService,
Expand All @@ -32,7 +34,7 @@ export class RecipientAccountHandler {
});

if (!recipient) {
console.error(
this.logger.error(
`Recipient not found for recipientId '${recipientId}' while updating user payment method!`,
);
return;
Expand Down Expand Up @@ -84,7 +86,7 @@ export class RecipientAccountHandler {
});

if (!recipient) {
console.error(
this.logger.error(
`Recipient not found for recipientId '${recipientId}' while updating user payment method!`,
);
return;
Expand Down Expand Up @@ -155,7 +157,7 @@ export class RecipientAccountHandler {
});

if (!recipientPaymentMethod) {
console.info(
this.logger.log(
`Recipient payment method not found for recipient account id '${payload.id}' while deleting trolley payment method!`,
);
return;
Expand Down
6 changes: 4 additions & 2 deletions src/api/webhooks/trolley/handlers/tax-form.handler.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Injectable } from '@nestjs/common';
import { Injectable, Logger } from '@nestjs/common';
import { WebhookEvent } from '../../webhooks.decorators';
import { PrismaService } from 'src/shared/global/prisma.service';
import { tax_form_status, trolley_recipient } from '@prisma/client';
Expand All @@ -12,6 +12,8 @@ import {

@Injectable()
export class TaxFormHandler {
private readonly logger = new Logger(TaxFormHandler.name);

constructor(
private readonly prisma: PrismaService,
private readonly paymentsService: PaymentsService,
Expand Down Expand Up @@ -95,7 +97,7 @@ export class TaxFormHandler {
const recipient = await this.getDbRecipientById(taxFormData.recipientId);

if (!recipient) {
console.error(
this.logger.error(
`Recipient not found for recipientId '${taxFormData.recipientId}' in taxForm with id '${taxFormData.taxFormId}'`,
);
return;
Expand Down
9 changes: 8 additions & 1 deletion src/api/webhooks/webhooks.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
Req,
RawBodyRequest,
ForbiddenException,
Logger,
} from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { TrolleyHeaders, TrolleyService } from './trolley/trolley.service';
Expand All @@ -13,6 +14,8 @@ import { Public } from 'src/core/auth/decorators';
@ApiTags('Webhooks')
@Controller('webhooks')
export class WebhooksController {
private readonly logger = new Logger(WebhooksController.name);

constructor(private readonly trolleyService: TrolleyService) {}

/**
Expand All @@ -34,12 +37,16 @@ export class WebhooksController {
request.rawBody?.toString('utf-8') ?? '',
)
) {
this.logger.warn(
'Received request with missing or invalid signature!',
request.headers,
);
throw new ForbiddenException('Missing or invalid signature!');
}

// do not proceed any further if event has already been processed
if (!(await this.trolleyService.validateUnique(request.headers))) {
console.info(
this.logger.warn(
`Webhook event '${request.headers[TrolleyHeaders.id]}' has already been processed!`,
);
return;
Expand Down
6 changes: 5 additions & 1 deletion src/api/winnings/winnings.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Injectable, HttpStatus } from '@nestjs/common';
import { Injectable, HttpStatus, Logger } from '@nestjs/common';
import { Prisma, payment, payment_status } from '@prisma/client';

import { PrismaService } from 'src/shared/global/prisma.service';
Expand All @@ -15,6 +15,8 @@ import { PaymentMethodRepository } from '../repository/paymentMethod.repo';
*/
@Injectable()
export class WinningsService {
private readonly logger = new Logger(WinningsService.name);

/**
* Constructs the admin winning service with the given dependencies.
* @param prisma the prisma service.
Expand Down Expand Up @@ -42,6 +44,8 @@ export class WinningsService {
const originId = await this.originRepo.getOriginIdByName(body.origin, tx);

if (!originId) {
this.logger.warn('Invalid origin provided', { originId });

result.error = {
code: HttpStatus.BAD_REQUEST,
message: 'Origin name does not exist',
Expand Down
5 changes: 4 additions & 1 deletion src/core/auth/middleware/tokenValidator.middleware.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import {
Injectable,
Logger,
NestMiddleware,
UnauthorizedException,
} from '@nestjs/common';
import * as jwt from 'jsonwebtoken';
import { ENV_CONFIG } from 'src/config';

const logger = new Logger(`Auth/TokenValidatorMiddleware`);

@Injectable()
export class TokenValidatorMiddleware implements NestMiddleware {
use(req: any, res: Response, next: (error?: any) => void) {
Expand All @@ -19,7 +22,7 @@ export class TokenValidatorMiddleware implements NestMiddleware {
try {
decoded = jwt.verify(idToken, ENV_CONFIG.AUTH0_CERT);
} catch (error) {
console.error('Error verifying JWT', error);
logger.error('Error verifying JWT', error);
throw new UnauthorizedException('Invalid or expired JWT!');
}

Expand Down
8 changes: 5 additions & 3 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import cors from 'cors';
import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import { ValidationPipe } from '@nestjs/common';
import { Logger, ValidationPipe } from '@nestjs/common';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { ApiModule } from './api/api.module';
import { AppModule } from './app.module';
Expand All @@ -18,6 +18,8 @@ async function bootstrap() {
rawBody: true,
});

const logger = new Logger('bootstrap()');

// Global prefix for all routes
app.setGlobalPrefix(ENV_CONFIG.API_BASE);

Expand Down Expand Up @@ -70,12 +72,12 @@ async function bootstrap() {

// Add an event handler to log uncaught promise rejections and prevent the server from crashing
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
logger.error('Unhandled Rejection at:', promise, 'reason:', reason);
});

// Add an event handler to log uncaught errors and prevent the server from crashing
process.on('uncaughtException', (error: Error) => {
console.error(
logger.error(
`Unhandled Error at: ${error}\n` + `Exception origin: ${error.stack}`,
);
});
Expand Down
40 changes: 38 additions & 2 deletions src/shared/global/prisma.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Injectable, OnModuleInit } from '@nestjs/common';
import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { Prisma, PrismaClient } from '@prisma/client';

@Injectable()
Expand All @@ -9,6 +9,8 @@ export class PrismaService
>
implements OnModuleInit
{
private readonly logger = new Logger(PrismaService.name);

constructor() {
super({
log: [
Expand All @@ -18,9 +20,43 @@ export class PrismaService
{ level: 'error', emit: 'event' },
],
});

// Setup logging for Prisma queries and errors
this.$on('query' as never, (e: Prisma.QueryEvent) => {
const queryTime = e.duration;

// log slow queries (> 500ms)
if (queryTime > 500) {
this.logger.warn(
`Slow query detected! Duration: ${queryTime}ms | Query: ${e.query}`,
);
}
});

this.$on('info' as never, (e: Prisma.LogEvent) => {
this.logger.log(`Prisma Info: ${e.message}`);
});

this.$on('warn' as never, (e: Prisma.LogEvent) => {
this.logger.warn(`Prisma Warning: ${e.message}`);
});

this.$on('error' as never, (e: Prisma.LogEvent) => {
this.logger.error(`Prisma Error: ${e.message}`, e.target);
});
}

async onModuleInit() {
await this.$connect();
this.logger.log('Initializing Prisma connection');
try {
await this.$connect();
this.logger.log('Prisma connected successfully');
} catch (error) {
this.logger.error(
`Failed to connect to the database: ${error.message}`,
error.stack,
);
throw error;
}
}
}
Loading