Skip to content

refactor(api-service): logger to pinologger #8128

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 15 commits into from
Apr 16, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
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
23 changes: 11 additions & 12 deletions apps/api/migrations/encrypt-api-keys/encrypt-api-keys-migration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@ import { createHash } from 'crypto';
import { NestFactory } from '@nestjs/core';

import { AppModule } from '../../src/app.module';
import { getLogger } from '../../src/app/shared/services/logger.service';

const logger = getLogger('EncryptApiKeysMigration');

export async function encryptApiKeysMigration() {
// eslint-disable-next-line no-console
console.log('start migration - encrypt api keys');
logger.info('start migration - encrypt api keys');

const app = await NestFactory.create(AppModule, {
logger: false,
Expand All @@ -20,12 +22,10 @@ export async function encryptApiKeysMigration() {
const environments = await environmentRepository.find({});

for (const environment of environments) {
// eslint-disable-next-line no-console
console.log(`environment ${environment._id}`);
logger.info(`environment ${environment._id}`);

if (!environment.apiKeys) {
// eslint-disable-next-line no-console
console.log(`environment ${environment._id} - is not contains api keys, skipping..`);
logger.info(`environment ${environment._id} - is not contains api keys, skipping..`);
continue;
}

Expand All @@ -34,8 +34,7 @@ export async function encryptApiKeysMigration() {
isEncrypted(key.key);
})
) {
// eslint-disable-next-line no-console
console.log(`environment ${environment._id} - api keys are already encrypted, skipping..`);
logger.info(`environment ${environment._id} - api keys are already encrypted, skipping..`);
continue;
}

Expand All @@ -47,11 +46,11 @@ export async function encryptApiKeysMigration() {
$set: { apiKeys: updatePayload },
}
);
// eslint-disable-next-line no-console
console.log(`environment ${environment._id} - api keys updated`);

logger.info(`environment ${environment._id} - api keys updated`);
}
// eslint-disable-next-line no-console
console.log('end migration');

logger.info('end migration');
}

export function encryptApiKeysWithGuard(apiKeys: IApiKey[]): IEncryptedApiKey[] {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,24 +1,23 @@
import { IntegrationEntity } from '@novu/dal';
import { IntegrationRepository } from '@novu/dal';
import { IntegrationEntity, IntegrationRepository } from '@novu/dal';
import { ICredentialsDto, secureCredentials } from '@novu/shared';
import { encryptSecret } from '@novu/application-generic';
import { getLogger } from '../../src/app/shared/services/logger.service';

const logger = getLogger('EncryptCredentialsMigration');

export async function encryptOldCredentialsMigration() {
// eslint-disable-next-line no-console
console.log('start migration - encrypt credentials');
logger.info('start migration - encrypt credentials');

const integrationRepository = new IntegrationRepository();
const integrations = await integrationRepository.find({} as any);

for (const integration of integrations) {
// eslint-disable-next-line no-console
console.log(`integration ${integration._id}`);
logger.info(`integration ${integration._id}`);

const updatePayload: Partial<IntegrationEntity> = {};

if (!integration.credentials) {
// eslint-disable-next-line no-console
console.log(`integration ${integration._id} - is not contains credentials, skipping..`);
logger.info(`integration ${integration._id} - is not contains credentials, skipping..`);
continue;
}

Expand All @@ -30,16 +29,14 @@ export async function encryptOldCredentialsMigration() {
$set: updatePayload,
}
);
// eslint-disable-next-line no-console
console.log(`integration ${integration._id} - credentials updated`);
logger.info(`integration ${integration._id} - credentials updated`);
}
// eslint-disable-next-line no-console
console.log('end migration');
logger.info('end migration');
}

export function encryptCredentialsWithGuard(integration: IntegrationEntity): ICredentialsDto {
const encryptedCredentials: ICredentialsDto = {};
const credentials = integration.credentials;
const { credentials } = integration;

for (const key in credentials) {
const credential = credentials[key];
Expand All @@ -66,8 +63,7 @@ function alreadyEncrypted(credential: string, integration: IntegrationEntity, cr
const encrypted = credential.includes('nvsk.');

if (encrypted) {
// eslint-disable-next-line no-console
console.log(`integration ${integration._id} - credential ${credentialKey} is already updated`);
logger.info(`integration ${integration._id} - credential ${credentialKey} is already updated`);
}

return encrypted;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,26 +1,27 @@
import '../../src/config';
import { IntegrationRepository } from '@novu/dal';
import { NestFactory } from '@nestjs/core';
import { Logger } from '@nestjs/common';
import { AppModule } from '../../src/app.module';
import { getLogger } from '../../src/app/shared/services/logger.service';

const integrationRepository = new IntegrationRepository();
const MIGRATION_CONTEXT = 'Migration';

const logger = getLogger('SecureToBooleanMigration');

export async function run() {
const app = await NestFactory.create(AppModule);

Logger.log('Start migration - update credentials.secure from string to boolean', MIGRATION_CONTEXT);
logger.info('Start migration - update credentials.secure from string to boolean');

Logger.log('Updating from "true" to true...', MIGRATION_CONTEXT);
logger.info('Updating from "true" to true...');
const resultTrue = await updateTrueValues();
Logger.log(`Matched: ${resultTrue.matchedCount} Modified: ${resultTrue.modifiedCount} \n`, MIGRATION_CONTEXT);
logger.info(`Matched: ${resultTrue.matchedCount} Modified: ${resultTrue.modifiedCount} \n`);

Logger.log('Updating from "false" to false...', MIGRATION_CONTEXT);
logger.info('Updating from "false" to false...');
const resultFalse = await updateFalseValues();
Logger.log(`Matched: ${resultFalse.matchedCount} Modified: ${resultFalse.modifiedCount} \n`, MIGRATION_CONTEXT);
logger.info(`Matched: ${resultFalse.matchedCount} Modified: ${resultFalse.modifiedCount} \n`);

Logger.log('End migration.\n', MIGRATION_CONTEXT);
logger.info('End migration.\n');
await app.close();
}

Expand Down
8 changes: 2 additions & 6 deletions apps/api/src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-disable global-require */
import { DynamicModule, Logger, Module, Provider } from '@nestjs/common';
import { DynamicModule, Module, Provider } from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { cacheService, TracingModule } from '@novu/application-generic';
import { Client, NovuModule } from '@novu/framework/nest';
Expand Down Expand Up @@ -175,8 +175,4 @@ modules.push(
controllers: [],
providers,
})
export class AppModule {
constructor() {
Logger.log(`BOOTSTRAPPED NEST APPLICATION`);
}
}
export class AppModule {}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { HttpService } from '@nestjs/axios';
import { Injectable, Logger } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import { AxiosError } from 'axios';
import { PinoLogger } from '@novu/application-generic';
import { HubspotIdentifyFormCommand } from './hubspot-identify-form.command';

const LOG_CONTEXT = 'HubspotIdentifyFormUsecase';
Expand All @@ -10,7 +11,12 @@ export class HubspotIdentifyFormUsecase {
private readonly hubspotPortalId = '44416662';
private readonly hubspotFormId = 'fc39aa98-4285-4322-9514-52da978baae8';

constructor(private httpService: HttpService) {}
constructor(
private httpService: HttpService,
private logger: PinoLogger
) {
this.logger.setContext(this.constructor.name);
}

async execute(command: HubspotIdentifyFormCommand) {
try {
Expand All @@ -30,10 +36,10 @@ export class HubspotIdentifyFormUsecase {
},
};

await this.httpService.post(hubspotSubmitUrl, hubspotData);
this.httpService.post(hubspotSubmitUrl, hubspotData);
} catch (error) {
if (error instanceof AxiosError) {
Logger.error(
this.logger.error(
`Failed to submit to Hubspot message=${error.message}, status=${error.status}`,
{
organizationId: command.organizationId,
Expand Down
15 changes: 8 additions & 7 deletions apps/api/src/app/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import {
Header,
HttpCode,
HttpStatus,
Logger,
NotFoundException,
Param,
Post,
Expand All @@ -21,7 +20,7 @@ import { MemberEntity, MemberRepository, UserRepository } from '@novu/dal';
import { AuthGuard } from '@nestjs/passport';
import { PasswordResetFlowEnum, UserSessionData } from '@novu/shared';
import { ApiExcludeController, ApiTags } from '@nestjs/swagger';
import { buildOauthRedirectUrl } from '@novu/application-generic';
import { buildOauthRedirectUrl, PinoLogger } from '@novu/application-generic';
import { UserRegistrationBodyDto } from './dtos/user-registration.dto';
import { UserRegister } from './usecases/register/user-register.usecase';
import { UserRegisterCommand } from './usecases/register/user-register.command';
Expand Down Expand Up @@ -56,25 +55,27 @@ export class AuthController {
private authService: AuthService,
private userRegisterUsecase: UserRegister,
private loginUsecase: Login,
private switchEnvironmentUsecase: SwitchEnvironment,
private switchOrganizationUsecase: SwitchOrganization,
private memberRepository: MemberRepository,
private passwordResetRequestUsecase: PasswordResetRequest,
private passwordResetUsecase: PasswordReset,
private updatePasswordUsecase: UpdatePassword
) {}
private updatePasswordUsecase: UpdatePassword,
private logger: PinoLogger
) {
this.logger.setContext(this.constructor.name);
}

@Get('/github')
githubAuth() {
Logger.verbose('Checking Github Auth');
this.logger.trace('Checking Github Auth');

if (!process.env.GITHUB_OAUTH_CLIENT_ID || !process.env.GITHUB_OAUTH_CLIENT_SECRET) {
throw new BadRequestException(
'GitHub auth is not configured, please provide GITHUB_OAUTH_CLIENT_ID and GITHUB_OAUTH_CLIENT_SECRET as env variables'
);
}

Logger.verbose('Github Auth has all variables.');
this.logger.trace('Github Auth has all variables.');

return {
success: true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export class CommunityUserAuthGuard extends AuthGuard([PassportStrategyEnum.JWT,
private readonly logger: PinoLogger
) {
super();
this.logger.setContext(this.constructor.name);
}

getAuthenticateOptions(context: ExecutionContext): IAuthModuleOptions<any> {
Expand Down
3 changes: 2 additions & 1 deletion apps/api/src/app/billing/e2e/create-usage-records.e2e-ee.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
/* eslint-disable global-require */
import { Logger } from '@nestjs/common';
import sinon from 'sinon';
import { expect } from 'chai';
import { ApiServiceLevelEnum, StripeBillingIntervalEnum } from '@novu/shared';
// eslint-disable-next-line no-restricted-imports
import { StripeUsageTypeEnum } from '@novu/ee-billing/src/stripe/types';
// eslint-disable-next-line no-restricted-imports
import { Logger } from '@nestjs/common';

const mockMonthlyBusinessSubscription = {
id: 'subscription_id',
Expand Down
1 change: 1 addition & 0 deletions apps/api/src/app/billing/e2e/verify-customer.e2e-ee.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/* eslint-disable global-require */
// eslint-disable-next-line no-restricted-imports
import { Logger } from '@nestjs/common';
import sinon from 'sinon';
import { CommunityOrganizationRepository } from '@novu/dal';
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Injectable, Logger, NotFoundException } from '@nestjs/common';
import { Injectable, NotFoundException } from '@nestjs/common';
import { NotificationTemplateEntity, NotificationTemplateRepository } from '@novu/dal';
import { buildGroupedBlueprintsKey, CachedResponse } from '@novu/application-generic';
import { buildGroupedBlueprintsKey, CachedResponse, PinoLogger } from '@novu/application-generic';
import { IGroupedBlueprint } from '@novu/shared';

import { GroupedBlueprintResponse } from '../../dto/grouped-blueprint.response.dto';
Expand All @@ -10,7 +10,12 @@ const WEEK_IN_SECONDS = 60 * 60 * 24 * 7;

@Injectable()
export class GetGroupedBlueprints {
constructor(private notificationTemplateRepository: NotificationTemplateRepository) {}
constructor(
private notificationTemplateRepository: NotificationTemplateRepository,
private logger: PinoLogger
) {
this.logger.setContext(this.constructor.name);
}

@CachedResponse({
builder: (command: GetGroupedBlueprintsCommand) => buildGroupedBlueprintsKey(command.environmentId),
Expand Down Expand Up @@ -54,7 +59,7 @@ export class GetGroupedBlueprints {
const storedBlueprint = storedBlueprints.find((blueprint) => blueprint._id === localPopularId);

if (!storedBlueprint) {
Logger.warn(
this.logger.warn(
`Could not find stored popular blueprint id: ${localPopularId}, BLUEPRINT_CREATOR:
${NotificationTemplateRepository.getBlueprintOrganizationId()}`
);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Logger, Injectable } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import { HealthCheck, GetActionEnum } from '@novu/framework/internal';
import { ExecuteBridgeRequest, ExecuteBridgeRequestCommand, ExecuteBridgeRequestDto } from '@novu/application-generic';
import { WorkflowOriginEnum } from '@novu/shared';
Expand Down
6 changes: 4 additions & 2 deletions apps/api/src/app/change/change.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import {
DynamicModule,
forwardRef,
ForwardReference,
Logger,
MiddlewareConsumer,
Module,
NestModule,
Expand All @@ -13,6 +12,9 @@ import { SharedModule } from '../shared/shared.module';
import { ChangesController } from './changes.controller';
import { USE_CASES } from './usecases';
import { AuthModule } from '../auth/auth.module';
import { getLogger } from '../shared/services/logger.service';

const logger = getLogger('ChangeModule');

const enterpriseImports = (): Array<Type | DynamicModule | Promise<DynamicModule> | ForwardReference> => {
const modules: Array<Type | DynamicModule | Promise<DynamicModule> | ForwardReference> = [];
Expand All @@ -23,7 +25,7 @@ const enterpriseImports = (): Array<Type | DynamicModule | Promise<DynamicModule
}
}
} catch (e) {
Logger.error(e, `Unexpected error while importing enterprise modules`, 'EnterpriseImport');
logger.error(e, `Unexpected error while importing enterprise modules`, 'EnterpriseImport');
}

return modules;
Expand Down
Loading
Loading