Skip to content

Commit

Permalink
refactor: use custom logger instead of nest
Browse files Browse the repository at this point in the history
  • Loading branch information
dnechay committed Feb 10, 2025
1 parent 0afe418 commit 80adf79
Show file tree
Hide file tree
Showing 41 changed files with 235 additions and 225 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@ import {
Catch,
ExceptionFilter as IExceptionFilter,
HttpStatus,
Logger,
HttpException,
} from '@nestjs/common';
import { Request, Response } from 'express';
import { DatabaseError } from '../errors/database';
import logger from '../../logger';

@Catch()
export class ExceptionFilter implements IExceptionFilter {
private logger = new Logger(ExceptionFilter.name);
private readonly logger = logger.child({ context: ExceptionFilter.name });

catch(exception: any, host: ArgumentsHost) {
const ctx = host.switchToHttp();
Expand All @@ -27,10 +27,7 @@ export class ExceptionFilter implements IExceptionFilter {
status = HttpStatus.UNPROCESSABLE_ENTITY;
responseBody.message = exception.message;

this.logger.error(
`Database error: ${exception.message}`,
exception.stack,
);
this.logger.error('Database error', exception);
// Temp hack for the in progress exception handling refactoring
} else if (exception instanceof HttpException) {
status = exception.getStatus();
Expand All @@ -41,10 +38,7 @@ export class ExceptionFilter implements IExceptionFilter {
Object.assign(responseBody, exceptionResponse);
}
} else {
this.logger.error(
`Unhandled exception: ${exception.message}`,
exception.stack,
);
this.logger.error('Unhandled exception', exception);
}

response.status(status).json(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,16 @@ import {
ExecutionContext,
HttpStatus,
HttpException,
Logger,
} from '@nestjs/common';
import { Request } from 'express';
import { HCaptchaService } from '../../integrations/hcaptcha/hcaptcha.service';
import { AuthConfigService } from '../config/auth-config.service';
import logger from '../../logger';

@Injectable()
export class HCaptchaGuard implements CanActivate {
logger = new Logger(HCaptchaGuard.name);
private readonly logger = logger.child({ context: HCaptchaGuard.name });

constructor(
private readonly hCaptchaService: HCaptchaService,
private readonly authConfigSerice: AuthConfigService,
Expand All @@ -37,7 +38,7 @@ export class HCaptchaGuard implements CanActivate {

if (!hCaptchaToken) {
const message = 'hCaptcha token not provided';
this.logger.error(message, request.path);
this.logger.error(message, { requestPath: request.path });
throw new HttpException(message, HttpStatus.BAD_REQUEST);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,16 @@ import {
ExecutionContext,
HttpStatus,
HttpException,
Logger,
} from '@nestjs/common';
import { Request } from 'express';
import { createHmac } from 'crypto';
import { KycConfigService } from '../config/kyc-config.service';
import logger from '../../logger';

@Injectable()
export class KycWebhookAuthGuard implements CanActivate {
logger = new Logger(KycWebhookAuthGuard.name);
private readonly logger = logger.child({ context: KycWebhookAuthGuard.name });

constructor(private readonly kycConfigService: KycConfigService) {}
canActivate(context: ExecutionContext): boolean {
const request: Request = context.switchToHttp().getRequest();
Expand All @@ -23,7 +24,7 @@ export class KycWebhookAuthGuard implements CanActivate {

if (!hmacSignature) {
const message = 'HMAC Signature not provided';
this.logger.error(message, request.path);
this.logger.error(message, { requestPath: request.path });
throw new HttpException(message, HttpStatus.UNAUTHORIZED);
}

Expand All @@ -39,7 +40,7 @@ export class KycWebhookAuthGuard implements CanActivate {
this.kycConfigService.apiKey !== apiKey
) {
const message = 'HMAC Signature does not match';
this.logger.error(message, request.path);
this.logger.error(message, { requestPath: request.path });
throw new HttpException(message, HttpStatus.UNAUTHORIZED);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,17 @@ import {
HttpException,
HttpStatus,
Injectable,
Logger,
} from '@nestjs/common';
import { verifySignature } from '../utils/signature';
import { HEADER_SIGNATURE_KEY } from '../constants';
import { EscrowUtils } from '@human-protocol/sdk';
import { AuthSignatureRole } from '../enums/role';
import logger from '../../logger';

@Injectable()
export class SignatureAuthGuard implements CanActivate {
logger = new Logger(SignatureAuthGuard.name);
private readonly logger = logger.child({ context: SignatureAuthGuard.name });

constructor(private role: AuthSignatureRole[]) {}

public async canActivate(context: ExecutionContext): Promise<boolean> {
Expand Down Expand Up @@ -46,7 +47,7 @@ export class SignatureAuthGuard implements CanActivate {

if (!isVerified) {
const message = 'Invalid web3 signature';
this.logger.error(message, request.path);
this.logger.error(message, { requestPath: request.path });
throw new HttpException(message, HttpStatus.UNAUTHORIZED);
}
return true;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { Logger, Module } from '@nestjs/common';
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { HCaptchaService } from './hcaptcha.service';
import { HttpModule } from '@nestjs/axios';

@Module({
imports: [ConfigModule, HttpModule],
providers: [Logger, HCaptchaService],
providers: [HCaptchaService],
exports: [HCaptchaService],
})
export class HCaptchaModule {}
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
import { Injectable, Logger } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { Injectable } from '@nestjs/common';
import { firstValueFrom } from 'rxjs';
import {
hCaptchaGetLabeler,
hCaptchaRegisterLabeler,
hCaptchaVerifyToken,
} from './hcaptcha.dto';
import { HttpService } from '@nestjs/axios';
import { firstValueFrom } from 'rxjs';
import { HCaptchaConfigService } from '../../common/config/hcaptcha-config.service';
import logger from '../../logger';

@Injectable()
export class HCaptchaService {
private readonly logger = new Logger(HCaptchaService.name);
private readonly logger = logger.child({ context: HCaptchaService.name });

constructor(
private httpService: HttpService,
Expand Down Expand Up @@ -51,12 +52,12 @@ export class HCaptchaService {
) {
return response.data;
} else if (response && response.data.success === false) {
this.logger.error(
`Error occurred during token verification: ${response.data['error-codes']}`,
);
this.logger.error('Error occurred during token verification', {
errorCodes: response.data['error-codes'],
});
}
} catch (error) {
this.logger.error(`Error occurred during token verification: ${error}`);
this.logger.error('Error occurred during token verification', error);
}

return false;
Expand Down Expand Up @@ -99,10 +100,10 @@ export class HCaptchaService {
return true;
}
} catch (error) {
this.logger.error(
`Error occurred during labeling registration. User: ${data.email}`,
this.logger.error('Error occurred during labeling registration', {
error,
);
userEmail: data.email,
});
}

return false;
Expand Down Expand Up @@ -130,10 +131,10 @@ export class HCaptchaService {
return response.data;
}
} catch (error) {
this.logger.error(
`Error occurred while retrieving labeler data. User: ${data.email}`,
this.logger.error(`Error occurred while retrieving labeler data`, {
error,
);
userEmail: data.email,
});
}

return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import {
Req,
UseGuards,
UseInterceptors,
Logger,
UseFilters,
HttpCode,
} from '@nestjs/common';
Expand Down Expand Up @@ -42,8 +41,6 @@ import {
@Controller('/auth')
@UseFilters(AuthControllerErrorsFilter)
export class AuthJwtController {
private readonly logger = new Logger(AuthJwtController.name);

constructor(
private readonly authService: AuthService,
private readonly tokenRepository: TokenRepository,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import {
Catch,
ArgumentsHost,
HttpStatus,
Logger,
} from '@nestjs/common';
import { Request, Response } from 'express';

Expand All @@ -14,6 +13,8 @@ import {
InvalidOperatorSignupDataError,
} from './auth.error';

import logger from '../../logger';

type AuthControllerError =
| AuthError
| DuplicatedUserEmailError
Expand All @@ -27,26 +28,26 @@ type AuthControllerError =
InvalidOperatorSignupDataError,
)
export class AuthControllerErrorsFilter implements ExceptionFilter {
private logger = new Logger(AuthControllerErrorsFilter.name);
private readonly logger = logger.child({
context: AuthControllerErrorsFilter.name,
});

catch(exception: AuthControllerError, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
let status = HttpStatus.UNAUTHORIZED;

let logContext: string | undefined;
if (exception instanceof DuplicatedUserEmailError) {
status = HttpStatus.CONFLICT;
logContext = exception.email;
} else if (exception instanceof DuplicatedUserAddressError) {
if (
exception instanceof DuplicatedUserEmailError ||
exception instanceof DuplicatedUserAddressError
) {
status = HttpStatus.CONFLICT;
logContext = exception.address;
} else if (exception instanceof InvalidOperatorSignupDataError) {
status = HttpStatus.BAD_REQUEST;
logContext = exception.detail;
}

this.logger.error(exception.message, exception.stack, logContext);
this.logger.error('Auth error', exception);

return response.status(status).json({
message: exception.message,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { Test, TestingModule } from '@nestjs/testing';
import { CronJobService } from './cron-job.service';
import { Logger } from '@nestjs/common';
import { CronJobRepository } from './cron-job.repository';
import { CronJobEntity } from './cron-job.entity';
import { CronJobType } from '../../common/enums/cron-job';
Expand Down Expand Up @@ -47,13 +46,6 @@ describe('CronJobService', () => {
processAwaitingPayouts: jest.fn(),
},
},
{
provide: Logger,
useValue: {
log: jest.fn(),
error: jest.fn(),
},
},
],
}).compile();

Expand Down
Loading

0 comments on commit 80adf79

Please sign in to comment.