Skip to content

Commit 38980d3

Browse files
authored
Merge pull request #44 from topcoder-platform/use-nest-logger
Use nest's logger instead of console.log
2 parents d6a218f + 237e362 commit 38980d3

File tree

13 files changed

+110
-32
lines changed

13 files changed

+110
-32
lines changed

src/api/admin/admin.service.ts

+6-3
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import {
33
HttpStatus,
44
NotFoundException,
55
BadRequestException,
6+
Logger,
67
} from '@nestjs/common';
78

89
import { PrismaPromise } from '@prisma/client';
@@ -21,6 +22,8 @@ import { WinningUpdateRequestDto } from './dto/winnings.dto';
2122
*/
2223
@Injectable()
2324
export class AdminService {
25+
private readonly logger = new Logger(AdminService.name);
26+
2427
/**
2528
* Constructs the admin winning service with the given dependencies.
2629
* @param prisma the prisma service.
@@ -279,7 +282,7 @@ export class AdminService {
279282
) {
280283
throw error;
281284
}
282-
console.error('Updating winnings failed', error);
285+
this.logger.error('Updating winnings failed', error);
283286
const message = 'Updating winnings failed. ' + error;
284287
result.error = {
285288
code: HttpStatus.INTERNAL_SERVER_ERROR,
@@ -477,7 +480,7 @@ export class AdminService {
477480
createdAt: item.created_at,
478481
}));
479482
} catch (error) {
480-
console.error('Getting winnings audit failed', error);
483+
this.logger.error('Getting winnings audit failed', error);
481484
const message = 'Searching winnings failed. ' + error;
482485
result.error = {
483486
code: HttpStatus.INTERNAL_SERVER_ERROR,
@@ -536,7 +539,7 @@ export class AdminService {
536539
externalTransactionDetails: {},
537540
}));
538541
} catch (error) {
539-
console.error('Getting winnings audit failed', error);
542+
this.logger.error('Getting winnings audit failed', error);
540543
const message = 'Searching winnings failed. ' + error;
541544
result.error = {
542545
code: HttpStatus.INTERNAL_SERVER_ERROR,

src/api/health-check/healthCheck.controller.ts

+10-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,10 @@
1-
import { Controller, Get, Version, VERSION_NEUTRAL } from '@nestjs/common';
1+
import {
2+
Controller,
3+
Get,
4+
Logger,
5+
Version,
6+
VERSION_NEUTRAL,
7+
} from '@nestjs/common';
28
import { ApiOperation, ApiProperty, ApiTags } from '@nestjs/swagger';
39
import { Public } from 'src/core/auth/decorators';
410
import { PrismaService } from 'src/shared/global/prisma.service';
@@ -26,6 +32,8 @@ export class GetHealthCheckResponseDto {
2632
@ApiTags('Healthcheck')
2733
@Controller()
2834
export class HealthCheckController {
35+
private readonly logger = new Logger(HealthCheckController.name);
36+
2937
constructor(private readonly prisma: PrismaService) {}
3038

3139
@Public()
@@ -45,7 +53,7 @@ export class HealthCheckController {
4553
response.status = HealthCheckStatus.healthy;
4654
response.database = 'connected';
4755
} catch (error) {
48-
console.error('Health check failed', error);
56+
this.logger.error('Health check failed', error);
4957
response.status = HealthCheckStatus.unhealthy;
5058
}
5159

src/api/repository/winnings.repo.ts

+4-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { HttpStatus, Injectable } from '@nestjs/common';
1+
import { HttpStatus, Injectable, Logger } from '@nestjs/common';
22
import {
33
payment_status,
44
Prisma,
@@ -20,6 +20,8 @@ const ONE_DAY = 24 * 60 * 60 * 1000;
2020

2121
@Injectable()
2222
export class WinningsRepository {
23+
private readonly logger = new Logger(WinningsRepository.name);
24+
2325
constructor(private readonly prisma: PrismaService) {}
2426

2527
private generateFilterDate(date: DateFilterType) {
@@ -243,7 +245,7 @@ export class WinningsRepository {
243245
};
244246
// response.data = winnings as any
245247
} catch (error) {
246-
console.error('Searching winnings failed', error);
248+
this.logger.error('Searching winnings failed', error);
247249
const message = 'Searching winnings failed. ' + error;
248250
result.error = {
249251
code: HttpStatus.INTERNAL_SERVER_ERROR,

src/api/wallet/wallet.service.ts

+6-4
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Injectable, HttpStatus } from '@nestjs/common';
1+
import { Injectable, HttpStatus, Logger } from '@nestjs/common';
22

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

@@ -13,6 +13,8 @@ import { PaymentMethodRepository } from '../repository/paymentMethod.repo';
1313
*/
1414
@Injectable()
1515
export class WalletService {
16+
private readonly logger = new Logger(WalletService.name);
17+
1618
/**
1719
* Constructs the admin winning service with the given dependencies.
1820
* @param prisma the prisma service.
@@ -60,16 +62,16 @@ export class WalletService {
6062
],
6163
},
6264
withdrawalMethod: {
63-
isSetupComplete: hasVerifiedPaymentMethod,
65+
isSetupComplete: Boolean(hasVerifiedPaymentMethod),
6466
},
6567
taxForm: {
66-
isSetupComplete: hasActiveTaxForm,
68+
isSetupComplete: Boolean(hasActiveTaxForm),
6769
},
6870
};
6971

7072
result.data = winningTotals;
7173
} catch (error) {
72-
console.error('Getting winnings audit failed', error);
74+
this.logger.error('Getting winnings audit failed', error);
7375
const message = 'Searching winnings failed. ' + error;
7476
result.error = {
7577
code: HttpStatus.INTERNAL_SERVER_ERROR,

src/api/webhooks/trolley/handlers/recipient-account.handler.ts

+6-4
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Injectable } from '@nestjs/common';
1+
import { Injectable, Logger } from '@nestjs/common';
22
import { WebhookEvent } from '../../webhooks.decorators';
33
import { PrismaService } from 'src/shared/global/prisma.service';
44
import {
@@ -11,6 +11,8 @@ import { PaymentsService } from 'src/shared/payments';
1111

1212
@Injectable()
1313
export class RecipientAccountHandler {
14+
private readonly logger = new Logger(RecipientAccountHandler.name);
15+
1416
constructor(
1517
private readonly prisma: PrismaService,
1618
private readonly paymentsService: PaymentsService,
@@ -32,7 +34,7 @@ export class RecipientAccountHandler {
3234
});
3335

3436
if (!recipient) {
35-
console.error(
37+
this.logger.error(
3638
`Recipient not found for recipientId '${recipientId}' while updating user payment method!`,
3739
);
3840
return;
@@ -84,7 +86,7 @@ export class RecipientAccountHandler {
8486
});
8587

8688
if (!recipient) {
87-
console.error(
89+
this.logger.error(
8890
`Recipient not found for recipientId '${recipientId}' while updating user payment method!`,
8991
);
9092
return;
@@ -155,7 +157,7 @@ export class RecipientAccountHandler {
155157
});
156158

157159
if (!recipientPaymentMethod) {
158-
console.info(
160+
this.logger.log(
159161
`Recipient payment method not found for recipient account id '${payload.id}' while deleting trolley payment method!`,
160162
);
161163
return;

src/api/webhooks/trolley/handlers/tax-form.handler.ts

+4-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Injectable } from '@nestjs/common';
1+
import { Injectable, Logger } from '@nestjs/common';
22
import { WebhookEvent } from '../../webhooks.decorators';
33
import { PrismaService } from 'src/shared/global/prisma.service';
44
import { tax_form_status, trolley_recipient } from '@prisma/client';
@@ -12,6 +12,8 @@ import {
1212

1313
@Injectable()
1414
export class TaxFormHandler {
15+
private readonly logger = new Logger(TaxFormHandler.name);
16+
1517
constructor(
1618
private readonly prisma: PrismaService,
1719
private readonly paymentsService: PaymentsService,
@@ -95,7 +97,7 @@ export class TaxFormHandler {
9597
const recipient = await this.getDbRecipientById(taxFormData.recipientId);
9698

9799
if (!recipient) {
98-
console.error(
100+
this.logger.error(
99101
`Recipient not found for recipientId '${taxFormData.recipientId}' in taxForm with id '${taxFormData.taxFormId}'`,
100102
);
101103
return;

src/api/webhooks/webhooks.controller.ts

+8-1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
Req,
55
RawBodyRequest,
66
ForbiddenException,
7+
Logger,
78
} from '@nestjs/common';
89
import { ApiTags } from '@nestjs/swagger';
910
import { TrolleyHeaders, TrolleyService } from './trolley/trolley.service';
@@ -13,6 +14,8 @@ import { Public } from 'src/core/auth/decorators';
1314
@ApiTags('Webhooks')
1415
@Controller('webhooks')
1516
export class WebhooksController {
17+
private readonly logger = new Logger(WebhooksController.name);
18+
1619
constructor(private readonly trolleyService: TrolleyService) {}
1720

1821
/**
@@ -34,12 +37,16 @@ export class WebhooksController {
3437
request.rawBody?.toString('utf-8') ?? '',
3538
)
3639
) {
40+
this.logger.warn(
41+
'Received request with missing or invalid signature!',
42+
request.headers,
43+
);
3744
throw new ForbiddenException('Missing or invalid signature!');
3845
}
3946

4047
// do not proceed any further if event has already been processed
4148
if (!(await this.trolleyService.validateUnique(request.headers))) {
42-
console.info(
49+
this.logger.warn(
4350
`Webhook event '${request.headers[TrolleyHeaders.id]}' has already been processed!`,
4451
);
4552
return;

src/api/winnings/winnings.service.ts

+5-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Injectable, HttpStatus } from '@nestjs/common';
1+
import { Injectable, HttpStatus, Logger } from '@nestjs/common';
22
import { Prisma, payment, payment_status } from '@prisma/client';
33

44
import { PrismaService } from 'src/shared/global/prisma.service';
@@ -15,6 +15,8 @@ import { PaymentMethodRepository } from '../repository/paymentMethod.repo';
1515
*/
1616
@Injectable()
1717
export class WinningsService {
18+
private readonly logger = new Logger(WinningsService.name);
19+
1820
/**
1921
* Constructs the admin winning service with the given dependencies.
2022
* @param prisma the prisma service.
@@ -42,6 +44,8 @@ export class WinningsService {
4244
const originId = await this.originRepo.getOriginIdByName(body.origin, tx);
4345

4446
if (!originId) {
47+
this.logger.warn('Invalid origin provided', { originId });
48+
4549
result.error = {
4650
code: HttpStatus.BAD_REQUEST,
4751
message: 'Origin name does not exist',

src/core/auth/middleware/tokenValidator.middleware.ts

+4-1
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
import {
22
Injectable,
3+
Logger,
34
NestMiddleware,
45
UnauthorizedException,
56
} from '@nestjs/common';
67
import * as jwt from 'jsonwebtoken';
78
import { ENV_CONFIG } from 'src/config';
89

10+
const logger = new Logger(`Auth/TokenValidatorMiddleware`);
11+
912
@Injectable()
1013
export class TokenValidatorMiddleware implements NestMiddleware {
1114
use(req: any, res: Response, next: (error?: any) => void) {
@@ -19,7 +22,7 @@ export class TokenValidatorMiddleware implements NestMiddleware {
1922
try {
2023
decoded = jwt.verify(idToken, ENV_CONFIG.AUTH0_CERT);
2124
} catch (error) {
22-
console.error('Error verifying JWT', error);
25+
logger.error('Error verifying JWT', error);
2326
throw new UnauthorizedException('Invalid or expired JWT!');
2427
}
2528

src/main.ts

+5-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import cors from 'cors';
22
import { NestFactory } from '@nestjs/core';
33
import { NestExpressApplication } from '@nestjs/platform-express';
4-
import { ValidationPipe } from '@nestjs/common';
4+
import { Logger, ValidationPipe } from '@nestjs/common';
55
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
66
import { ApiModule } from './api/api.module';
77
import { AppModule } from './app.module';
@@ -18,6 +18,8 @@ async function bootstrap() {
1818
rawBody: true,
1919
});
2020

21+
const logger = new Logger('bootstrap()');
22+
2123
// Global prefix for all routes
2224
app.setGlobalPrefix(ENV_CONFIG.API_BASE);
2325

@@ -70,12 +72,12 @@ async function bootstrap() {
7072

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

7678
// Add an event handler to log uncaught errors and prevent the server from crashing
7779
process.on('uncaughtException', (error: Error) => {
78-
console.error(
80+
logger.error(
7981
`Unhandled Error at: ${error}\n` + `Exception origin: ${error.stack}`,
8082
);
8183
});

src/shared/global/prisma.service.ts

+38-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Injectable, OnModuleInit } from '@nestjs/common';
1+
import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
22
import { Prisma, PrismaClient } from '@prisma/client';
33

44
@Injectable()
@@ -9,6 +9,8 @@ export class PrismaService
99
>
1010
implements OnModuleInit
1111
{
12+
private readonly logger = new Logger(PrismaService.name);
13+
1214
constructor() {
1315
super({
1416
log: [
@@ -18,9 +20,43 @@ export class PrismaService
1820
{ level: 'error', emit: 'event' },
1921
],
2022
});
23+
24+
// Setup logging for Prisma queries and errors
25+
this.$on('query' as never, (e: Prisma.QueryEvent) => {
26+
const queryTime = e.duration;
27+
28+
// log slow queries (> 500ms)
29+
if (queryTime > 500) {
30+
this.logger.warn(
31+
`Slow query detected! Duration: ${queryTime}ms | Query: ${e.query}`,
32+
);
33+
}
34+
});
35+
36+
this.$on('info' as never, (e: Prisma.LogEvent) => {
37+
this.logger.log(`Prisma Info: ${e.message}`);
38+
});
39+
40+
this.$on('warn' as never, (e: Prisma.LogEvent) => {
41+
this.logger.warn(`Prisma Warning: ${e.message}`);
42+
});
43+
44+
this.$on('error' as never, (e: Prisma.LogEvent) => {
45+
this.logger.error(`Prisma Error: ${e.message}`, e.target);
46+
});
2147
}
2248

2349
async onModuleInit() {
24-
await this.$connect();
50+
this.logger.log('Initializing Prisma connection');
51+
try {
52+
await this.$connect();
53+
this.logger.log('Prisma connected successfully');
54+
} catch (error) {
55+
this.logger.error(
56+
`Failed to connect to the database: ${error.message}`,
57+
error.stack,
58+
);
59+
throw error;
60+
}
2561
}
2662
}

0 commit comments

Comments
 (0)