Skip to content

Commit

Permalink
fix: ORV2-1806 Resolve LogMethodExecution Decorator for non Async Met…
Browse files Browse the repository at this point in the history
…hods (#963)
  • Loading branch information
praju-aot authored Dec 23, 2023
1 parent 27a0af2 commit cd39a96
Show file tree
Hide file tree
Showing 27 changed files with 248 additions and 144 deletions.
4 changes: 2 additions & 2 deletions dops/src/app.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { createFile } from './helper/file.helper';
import { addToCache } from './helper/cache.helper';
import * as fs from 'fs';
import { DgenService } from './modules/dgen/dgen.service';
import { LogMethodExecution } from './decorator/log-method-execution.decorator';
import { LogAsyncMethodExecution } from './decorator/log-async-method-execution.decorator';

@Injectable()
export class AppService {
Expand All @@ -30,7 +30,7 @@ export class AppService {
return 'DOPS Healthcheck!';
}

@LogMethodExecution({ printMemoryStats: true })
@LogAsyncMethodExecution({ printMemoryStats: true })
async initializeCache() {
const startDateTime = new Date();
const templates = await this.dgenService.findAllTemplates();
Expand Down
43 changes: 43 additions & 0 deletions dops/src/decorator/log-async-method-execution.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { Logger } from '@nestjs/common';

export function LogAsyncMethodExecution(logMethodOptions?: {
printMemoryStats: boolean;
}) {
return function (
target: object,
propertyKey: string,
descriptor: PropertyDescriptor,
) {
let memoryUsage = '';
/* eslint-disable */
const logger = new Logger(target.constructor.name);
const originalMethod = descriptor.value;
descriptor.value = async function (...args: any[]) {
if (logMethodOptions?.printMemoryStats &&
process.env.DOPS_API_LOG_LEVEL === 'debug') {
const memoryStats = process.memoryUsage();
memoryUsage = `, Memory usage: ${JSON.stringify(memoryStats)}`;
}
logger.debug(
`>> Entering ${target.constructor.name}.${propertyKey} method${memoryUsage}`,
);

const start = performance.now();
const result = await originalMethod.apply(this, args);
const end = performance.now();
const executionTime = end - start;
if (logMethodOptions?.printMemoryStats &&
process.env.DOPS_API_LOG_LEVEL === 'debug') {
const memoryStats = process.memoryUsage();
memoryUsage = `, Memory usage: ${JSON.stringify(memoryStats)}`;
}
logger.debug(
`<< Exiting ${target.constructor.name}.${propertyKey} method, execution time: ${executionTime}ms${memoryUsage}`,
);
return result;
};
/* eslint-enable */

return descriptor;
};
}
14 changes: 10 additions & 4 deletions dops/src/decorator/log-method-execution.decorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,11 @@ export function LogMethodExecution(logMethodOptions?: {
/* eslint-disable */
const logger = new Logger(target.constructor.name);
const originalMethod = descriptor.value;
descriptor.value = async function (...args: any[]) {
if (logMethodOptions?.printMemoryStats) {
descriptor.value = function (...args: any[]) {
if (
logMethodOptions?.printMemoryStats &&
process.env.DOPS_API_LOG_LEVEL === 'debug'
) {
const memoryStats = process.memoryUsage();
memoryUsage = `, Memory usage: ${JSON.stringify(memoryStats)}`;
}
Expand All @@ -22,10 +25,13 @@ export function LogMethodExecution(logMethodOptions?: {
);

const start = performance.now();
const result = await originalMethod.apply(this, args);
const result = originalMethod.apply(this, args);
const end = performance.now();
const executionTime = end - start;
if (logMethodOptions?.printMemoryStats) {
if (
logMethodOptions?.printMemoryStats &&
process.env.DOPS_API_LOG_LEVEL === 'debug'
) {
const memoryStats = process.memoryUsage();
memoryUsage = `, Memory usage: ${JSON.stringify(memoryStats)}`;
}
Expand Down
8 changes: 4 additions & 4 deletions dops/src/modules/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { lastValueFrom } from 'rxjs';
import { ClsService } from 'nestjs-cls';
import { LogMethodExecution } from '../../decorator/log-method-execution.decorator';
import { LogAsyncMethodExecution } from '../../decorator/log-async-method-execution.decorator';

@Injectable()
export class AuthService {
Expand All @@ -16,7 +16,7 @@ export class AuthService {
private readonly cls: ClsService,
) {}

@LogMethodExecution()
@LogAsyncMethodExecution()
async getUserDetails(
accessToken: string,
userGuid: string,
Expand All @@ -42,7 +42,7 @@ export class AuthService {
*
* @returns The Roles as a promise of type {@link Role[]}
*/
@LogMethodExecution()
@LogAsyncMethodExecution()
async getRolesForUser(
accessToken: string,
companyId?: number,
Expand All @@ -67,7 +67,7 @@ export class AuthService {
*
* @returns The associated companies as a promise of type {@link number[]}
*/
@LogMethodExecution()
@LogAsyncMethodExecution()
async getCompaniesForUser(accessToken: string): Promise<AxiosResponse> {
return lastValueFrom(
this.httpService.get(process.env.ACCESS_API_URL + '/companies', {
Expand Down
4 changes: 2 additions & 2 deletions dops/src/modules/common/cdogs.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import {
FILE_TYPE_DOCX,
FILE_TYPE_PDF,
} from '../../constants/dops.constant';
import { LogMethodExecution } from '../../decorator/log-method-execution.decorator';
import { LogAsyncMethodExecution } from '../../decorator/log-async-method-execution.decorator';

@Injectable()
export class CdogsService {
Expand All @@ -44,7 +44,7 @@ export class CdogsService {
* @returns A Promise that resolves to an array of ReadCOMSDto objects
* representing the created objects.
*/
@LogMethodExecution()
@LogAsyncMethodExecution()
async generateDocument(
currentUser: IUserJWT,
createGeneratedDocumentDto: CreateGeneratedDocumentDto,
Expand Down
8 changes: 4 additions & 4 deletions dops/src/modules/common/s3.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { Response } from 'express';
import { IFile } from '../../interface/file.interface';
import { Upload } from '@aws-sdk/lib-storage';
import { LogMethodExecution } from '../../decorator/log-method-execution.decorator';
import { LogAsyncMethodExecution } from '../../decorator/log-async-method-execution.decorator';
@Injectable()
export class S3Service {
private readonly logger = new Logger(S3Service.name);
Expand All @@ -38,7 +38,7 @@ export class S3Service {
region: 'ca-central-1',
});

@LogMethodExecution()
@LogAsyncMethodExecution()
async uploadFile(
file: Express.Multer.File | IFile,
filePath?: string,
Expand All @@ -59,7 +59,7 @@ export class S3Service {
return (await upload.done()) as CompleteMultipartUploadCommandOutput;
}

@LogMethodExecution()
@LogAsyncMethodExecution()
async getFile(
filePath: string,
res?: Response,
Expand All @@ -79,7 +79,7 @@ export class S3Service {
}
}

@LogMethodExecution()
@LogAsyncMethodExecution()
async presignUrl(filePath: string): Promise<string> {
const params = {
Bucket: this._s3Bucket,
Expand Down
9 changes: 5 additions & 4 deletions dops/src/modules/dgen/dgen.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import puppeteer, { Browser } from 'puppeteer';
import { IFile } from '../../interface/file.interface';
import { ReportTemplate } from '../../enum/report-template.enum';
import { convertUtcToPt } from '../../helper/date-time.helper';
import { LogAsyncMethodExecution } from '../../decorator/log-async-method-execution.decorator';
import { LogMethodExecution } from '../../decorator/log-method-execution.decorator';

@Injectable()
Expand All @@ -52,12 +53,12 @@ export class DgenService {
* Find all templates registered in ORBC_DOCUMENT_TEMPLATE
* @returns A list of templates of type {@link DocumentTemplate}
*/
@LogMethodExecution()
@LogAsyncMethodExecution()
async findAllTemplates(): Promise<DocumentTemplate[]> {
return await this.documentTemplateRepository.find();
}

@LogMethodExecution()
@LogAsyncMethodExecution()
async getLatestTemplates(): Promise<DocumentTemplate[]> {
const latestTemplates = await this.documentTemplateRepository
.createQueryBuilder('documentTemplate')
Expand Down Expand Up @@ -91,7 +92,7 @@ export class DgenService {
});
}

@LogMethodExecution()
@LogAsyncMethodExecution()
async generate(
currentUser: IUserJWT,
createGeneratedDocumentDto: CreateGeneratedDocumentDto,
Expand Down Expand Up @@ -209,7 +210,7 @@ export class DgenService {
);
}

@LogMethodExecution({ printMemoryStats: true })
@LogAsyncMethodExecution({ printMemoryStats: true })
async generateReport(
currentUser: IUserJWT,
createGeneratedReportDto: CreateGeneratedReportDto,
Expand Down
12 changes: 6 additions & 6 deletions dops/src/modules/dms/dms.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { S3Service } from '../common/s3.service';
import { Response } from 'express';
import { v4 as uuidv4 } from 'uuid';
import { IDP } from '../../enum/idp.enum';
import { LogMethodExecution } from '../../decorator/log-method-execution.decorator';
import { LogAsyncMethodExecution } from '../../decorator/log-async-method-execution.decorator';

@Injectable()
export class DmsService {
Expand All @@ -29,7 +29,7 @@ export class DmsService {

private s3accessType = process.env.DOPS_S3_ACCESS_TYPE;

@LogMethodExecution()
@LogAsyncMethodExecution()
async create(
currentUser: IUserJWT,
file: Express.Multer.File | IFile,
Expand Down Expand Up @@ -67,7 +67,7 @@ export class DmsService {
);
}

@LogMethodExecution()
@LogAsyncMethodExecution()
async update(
currentUser: IUserJWT,
documentId: string,
Expand Down Expand Up @@ -110,7 +110,7 @@ export class DmsService {
);
}

@LogMethodExecution()
@LogAsyncMethodExecution()
async findOne(documentId: string): Promise<ReadFileDto> {
const readFile = this.classMapper.mapAsync(
await this.documentRepository.findOne({
Expand All @@ -122,7 +122,7 @@ export class DmsService {
return readFile;
}

@LogMethodExecution()
@LogAsyncMethodExecution()
async download(
currentUser: IUserJWT,
documentId: string,
Expand All @@ -149,7 +149,7 @@ export class DmsService {
return { file, s3Object };
}

@LogMethodExecution()
@LogAsyncMethodExecution()
async findLatest(documentId: string): Promise<ReadFileDto> {
const subQuery = this.documentRepository
.createQueryBuilder('document')
Expand Down
4 changes: 2 additions & 2 deletions vehicles/src/app.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import * as fs from 'fs';
import { CacheKey } from './common/enum/cache-key.enum';
import { addToCache, createCacheMap } from './common/helper/cache.helper';
import { PaymentService } from './modules/payment/payment.service';
import { LogMethodExecution } from './common/decorator/log-method-execution.decorator';
import { LogAsyncMethodExecution } from './common/decorator/log-async-method-execution.decorator';

@Injectable()
export class AppService {
Expand All @@ -29,7 +29,7 @@ export class AppService {
return 'Vehicles Healthcheck!';
}

@LogMethodExecution({ printMemoryStats: true })
@LogAsyncMethodExecution({ printMemoryStats: true })
async initializeCache() {
const startDateTime = new Date();
const countries = await this.commonService.findAllCountries();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { Logger } from '@nestjs/common';

export function LogAsyncMethodExecution(logMethodOptions?: {
printMemoryStats: boolean;
}) {
return function (
target: object,
propertyKey: string,
descriptor: PropertyDescriptor,
) {
let memoryUsage = '';
/* eslint-disable */
const logger = new Logger(target.constructor.name);
const originalMethod = descriptor.value;
descriptor.value = async function (...args: any[]) {
if (
logMethodOptions?.printMemoryStats &&
process.env.VEHICLES_API_LOG_LEVEL === 'debug'
) {
const memoryStats = process.memoryUsage();
memoryUsage = `, Memory usage: ${JSON.stringify(memoryStats)}`;
}
logger.debug(
`>> Entering ${target.constructor.name}.${propertyKey} method${memoryUsage}`,
);

const start = performance.now();
const result = await originalMethod.apply(this, args);
const end = performance.now();
const executionTime = end - start;
if (
logMethodOptions?.printMemoryStats &&
process.env.VEHICLES_API_LOG_LEVEL === 'debug'
) {
const memoryStats = process.memoryUsage();
memoryUsage = `, Memory usage: ${JSON.stringify(memoryStats)}`;
}
logger.debug(
`<< Exiting ${target.constructor.name}.${propertyKey} method, execution time: ${executionTime}ms${memoryUsage}`,
);
return result;
};
/* eslint-enable */

return descriptor;
};
}
14 changes: 10 additions & 4 deletions vehicles/src/common/decorator/log-method-execution.decorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,11 @@ export function LogMethodExecution(logMethodOptions?: {
/* eslint-disable */
const logger = new Logger(target.constructor.name);
const originalMethod = descriptor.value;
descriptor.value = async function (...args: any[]) {
if (logMethodOptions?.printMemoryStats) {
descriptor.value = function (...args: any[]) {
if (
logMethodOptions?.printMemoryStats &&
process.env.VEHICLES_API_LOG_LEVEL === 'debug'
) {
const memoryStats = process.memoryUsage();
memoryUsage = `, Memory usage: ${JSON.stringify(memoryStats)}`;
}
Expand All @@ -22,10 +25,13 @@ export function LogMethodExecution(logMethodOptions?: {
);

const start = performance.now();
const result = await originalMethod.apply(this, args);
const result = originalMethod.apply(this, args);
const end = performance.now();
const executionTime = end - start;
if (logMethodOptions?.printMemoryStats) {
if (
logMethodOptions?.printMemoryStats &&
process.env.VEHICLES_API_LOG_LEVEL === 'debug'
) {
const memoryStats = process.memoryUsage();
memoryUsage = `, Memory usage: ${JSON.stringify(memoryStats)}`;
}
Expand Down
Loading

0 comments on commit cd39a96

Please sign in to comment.