Skip to content
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

feat: improve logger injection in constructor #380

Merged
merged 2 commits into from
Jan 21, 2025

Conversation

Harish-osmosys
Copy link
Contributor

@Harish-osmosys Harish-osmosys commented Jan 8, 2025

API PR Checklist

Pre-requisites

  • I have gone through the Contributing guidelines for Submitting a Pull Request (PR) and ensured that this is not a duplicate PR.
  • I have performed unit testing for the new feature added or updated to ensure the new features added are working as expected.
  • I have added/updated test cases to the test suite as applicable.
  • I have performed preliminary testing using the test suite to ensure that any existing features are not impacted and any new features are working as expected as a whole.
  • I have added/updated the required api docs as applicable.
  • I have added/updated the .env.example file with the required values as applicable.

PR Details

PR details have been updated as per the given format (see below)

  • PR title adheres to the format specified in guidelines (e.g., feat: add admin login endpoint)
  • Description has been added
  • Related changes have been added (optional)
  • Screenshots have been added (optional)
  • Query request and response examples have been added (as applicable, in case added or updated)
  • Documentation changes have been listed (as applicable)
  • Test suite/unit testing output is added (as applicable)
  • Pending actions have been added (optional)
  • Any other additional notes have been added (optional)

Additional Information

  • Appropriate label(s) have been added (ready for review should be added if the PR is ready to be reviewed)
  • Assignee(s) and reviewer(s) have been added (optional)

Note: Reviewer should ensure that the checklist and description have been populated and followed correctly, and the PR should be merged only after resolving all conversations and verifying that CI checks pass.


Description:

  • Improve Logger Injection for Better Log Filtering and Debugging
  • Modify the existing Logger injection to include a context name for better log filtering and readability.

Related changes:

N/A

Screenshots:

N/A

Query request and response:

N/A

Documentation changes:

N/A

Test suite/unit testing output:

N/A

Pending actions:

N/A

Additional notes:

N/A

Summary by CodeRabbit

  • Refactor

    • Updated logger initialization across multiple services and classes to use default logger with class-specific context.
    • Simplified constructor signatures by making logger parameter optional with a default value.
  • Chores

    • Improved logging mechanism by ensuring consistent logger instantiation across different services.

@Harish-osmosys Harish-osmosys requested a review from xixas January 8, 2025 11:06
@Harish-osmosys Harish-osmosys self-assigned this Jan 8, 2025
Copy link

coderabbitai bot commented Jan 8, 2025

Walkthrough

The pull request introduces a consistent approach to logger initialization across multiple services and classes in the API. The changes modify the constructor signatures of various services and classes to provide a default logger using the class name. This standardization simplifies logger instantiation by removing the requirement to explicitly pass a logger instance, while ensuring each class has a contextually named logger for improved traceability and debugging.

Changes

File Path Change Summary
apps/api/src/common/decorators/is-data-valid.decorator.ts Added default logger initialization with class name
apps/api/src/common/guards/api-key/api-key.guard.ts Added default logger initialization with class name
apps/api/src/modules/notifications/notifications.controller.ts Added default logger initialization with class name
apps/api/src/modules/providers/*/ (Multiple files) Added default logger initialization with class name for services like AwsSes, Mailgun, PushSns, SmsKapsystem, SmsPivo, SmsSns, SmsTwilio, Smtp, VcTwilio, WaTwilioBusinessService, WaTwilio, Wa360dialog

Suggested labels

ready for review

Suggested reviewers

  • xixas

Poem

🐰 Logger's Dance, a Rabbit's Delight

With class names bright and logging so light,
No more passing loggers with might,
Default instances take their flight,
Simplifying code with pure delight!

  • CodeRabbit 🎩✨

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🔭 Outside diff range comments (2)
apps/api/src/modules/notifications/notifications.controller.ts (1)

Line range hint 31-32: Review logging of sensitive notification data.

The debug log contains raw notification data which might include PII. Consider implementing data masking.

-      this.logger.debug(`Notification Request Data: ${JSON.stringify(notificationData)}`);
+      this.logger.debug('Notification Request Data:', {
+        ...notificationData,
+        message: notificationData.message ? '[MASKED]' : undefined,
+        to: notificationData.to ? '[MASKED]' : undefined
+      });
apps/api/src/common/guards/api-key/api-key.guard.ts (1)

Line range hint 29-63: Consider refactoring to reduce code duplication.

The validation logic for HTTP and GraphQL requests contains duplicate code.

Consider extracting the common validation logic:

+  private async validateApiKeyAndProviderId(
+    headers: Record<string, string>,
+    providerId: number
+  ): Promise<boolean> {
+    const serverApiKeyHeader = headers['x-api-key'];
+    return await this.validateApiKeyHeader(serverApiKeyHeader, providerId);
+  }
+
   async validateRequest(execContext: ExecutionContext): Promise<boolean> {
     const request = execContext.switchToHttp().getRequest();
     this.logger.debug(
       `Request validation started for request body: ${JSON.stringify(request.body)}`,
     );
 
     // Get api key header incase of http request
     if (request && request.headers) {
-      this.logger.debug(`Fetching request header and provider ID: ${request.body.providerId}`);
-      const serverApiKeyHeader = request.headers['x-api-key'];
-      this.logger.debug('Fetching provider Id');
       const requestProviderId = request.body.providerId;
-      const validationResult = await this.validateApiKeyHeader(
-        serverApiKeyHeader,
-        requestProviderId,
-      );
+      const validationResult = await this.validateApiKeyAndProviderId(
+        request.headers,
+        requestProviderId
+      );
 
       if (validationResult) {
         return true;
       }
     }
 
     // Get api key header incase of graphql request
     const ctx = GqlExecutionContext.create(execContext);
     const req = ctx.getContext().req;
-    this.logger.debug(
-      `Fetching request header and provider ID for GraphQL: ${req.body.providerId}`,
-    );
-    const serverApiKeyHeader = req.headers['x-api-key'];
     const requestProviderId = request.body.providerId;
-    const validationResult = await this.validateApiKeyHeader(serverApiKeyHeader, requestProviderId);
+    const validationResult = await this.validateApiKeyAndProviderId(
+      req.headers,
+      requestProviderId
+    );
 
     if (validationResult) {
       return true;
     }
🧹 Nitpick comments (8)
apps/api/src/modules/providers/sms-sns/sms-sns.service.ts (1)

Line range hint 21-33: Excellent error handling with appropriate logging!

The try-catch blocks with error logging provide good traceability for debugging. Consider adding error codes or identifiers for better error tracking.

 } catch (error) {
-      this.logger.error('Error assigning SNS configuration', error);
+      this.logger.error('Error assigning SNS configuration', {
+        errorCode: 'SNS_CONFIG_ERROR',
+        error: error.message
+      });
       throw error;

Also applies to: 44-49

apps/api/src/modules/providers/wa360dialog/wa360dialog.service.ts (1)

54-54: LGTM! Consider enhancing error logging structure.

The logger initialization is consistent with other services. However, the error logging in the sendMessage method could be improved.

Consider structuring the error logging to include more context:

-this.logger.error(`Error sent from provider: ${providerId}`, providerResponseError);
+this.logger.error('Provider request failed', {
+  providerId,
+  error: providerResponseError,
+  endpoint: this.apiUrl
+});
apps/api/src/modules/providers/wa-twilio-business/wa-twilio-business.service.ts (2)

41-41: LGTM! Consider standardizing error handling.

The logger initialization is consistent with other services. However, the error handling could be standardized across all Twilio services.

Consider adopting a consistent error handling pattern across all Twilio services:

-throw new Error(`Failed to fetch delivery status: ${error.message}`);
+this.logger.error('Failed to fetch delivery status', {
+  providerId,
+  sid,
+  error: error.message
+});
+throw error;

Line range hint 37-54: Consider creating a base provider service.

Given the similar patterns across all provider services (logger initialization, error handling, transport assignment), consider creating an abstract base provider service to standardize these common behaviors.

This would help:

  1. Standardize error handling across all providers
  2. Provide consistent logging patterns
  3. Reduce code duplication
  4. Simplify testing

Example structure:

abstract class BaseProviderService {
  protected constructor(
    protected readonly providersService: ProvidersService,
    protected readonly logger: Logger
  ) {
    this.logger = new Logger(this.constructor.name);
  }

  protected handleError(error: any, context: object) {
    this.logger.error('Provider operation failed', { ...context, error });
    throw error;
  }
}
apps/api/src/modules/providers/sms-plivo/sms-plivo.service.ts (1)

Line range hint 84-92: Consider standardizing error handling structure.

The error handling differentiates between provider API errors and other errors, but could be more structured.

Consider this pattern:

     } catch (error) {
-      if (error.apiID) {
-        // Log relevant parts of the error response
-        this.logger.error(`Error sent from provider: ${providerId}`, error.message);
-        throw error;
-      } else {
-        // Handle cases where there is no response (network issues, etc.)
-        throw new Error(`Failed to send message: ${error.message}`);
-      }
+      if (!error.apiID) {
+        throw new Error(`Network or configuration error: ${error.message}`);
+      }
+      this.logger.error({
+        message: `Provider error for ID: ${providerId}`,
+        error: {
+          apiId: error.apiID,
+          message: error.message
+        }
+      });
+      throw error;
     }
apps/api/src/modules/providers/mailgun/mailgun.service.ts (1)

Line range hint 82-89: Consider enhancing attachment error handling.

The attachment processing could benefit from more detailed error handling and validation.

Consider adding validation and more specific error types:

       if (attachment.path) {
         try {
           const filepath = path.resolve(attachment.path);
+          // Validate file exists before reading
+          await fs.access(filepath);
           data = await fs.readFile(filepath);
         } catch (error) {
+          if (error.code === 'ENOENT') {
+            throw new BadRequestException(`File not found at path: ${attachment.path}`);
+          }
           throw new BadRequestException(
             `Failed to read file at path: ${attachment.path}: ${error.message}`,
           );
         }
       }
apps/api/src/modules/providers/vc-twilio/vc-twilio.service.ts (1)

90-90: LGTM! Consider enhancing error logging.

The logger initialization change looks good and aligns with the PR objectives. However, consider enhancing error logging in the catch blocks to include the error stack trace for better debugging.

 } catch (error) {
-  throw new Error(`Failed to send voice call: ${error.message}`);
+  this.logger.error('Failed to send voice call', { error });
+  throw new Error(`Failed to send voice call: ${error.message}`);
 }
apps/api/src/common/decorators/is-data-valid.decorator.ts (1)

33-33: LGTM! Consider enhancing validation error logging.

The logger initialization change is consistent with the PR objectives. However, the validation error handling could benefit from improved logging.

 if (errors.length > 0) {
   const validationErrors = errors.map((obj) => Object.values(obj.constraints));
+  this.logger.debug('Validation failed', { errors: validationErrors });
   throw new BadRequestException(...validationErrors);
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ca08424 and 851f419.

📒 Files selected for processing (15)
  • apps/api/src/common/decorators/is-data-valid.decorator.ts (1 hunks)
  • apps/api/src/common/guards/api-key/api-key.guard.ts (1 hunks)
  • apps/api/src/modules/notifications/notifications.controller.ts (1 hunks)
  • apps/api/src/modules/providers/aws-ses/aws-ses.service.ts (1 hunks)
  • apps/api/src/modules/providers/mailgun/mailgun.service.ts (1 hunks)
  • apps/api/src/modules/providers/push-sns/push-sns.service.ts (1 hunks)
  • apps/api/src/modules/providers/sms-kapsystem/sms-kapsystem.service.ts (1 hunks)
  • apps/api/src/modules/providers/sms-plivo/sms-plivo.service.ts (1 hunks)
  • apps/api/src/modules/providers/sms-sns/sms-sns.service.ts (1 hunks)
  • apps/api/src/modules/providers/sms-twilio/sms-twilio.service.ts (1 hunks)
  • apps/api/src/modules/providers/smtp/smtp.service.ts (1 hunks)
  • apps/api/src/modules/providers/vc-twilio/vc-twilio.service.ts (1 hunks)
  • apps/api/src/modules/providers/wa-twilio-business/wa-twilio-business.service.ts (1 hunks)
  • apps/api/src/modules/providers/wa-twilio/wa-twilio.service.ts (1 hunks)
  • apps/api/src/modules/providers/wa360dialog/wa360dialog.service.ts (1 hunks)
🧰 Additional context used
📓 Learnings (1)
apps/api/src/modules/notifications/notifications.controller.ts (1)
Learnt from: LakshayaT
PR: OsmosysSoftware/osmo-x#293
File: apps/api/src/modules/notifications/notifications.controller.ts:15-18
Timestamp: 2024-11-12T07:51:34.599Z
Learning: The `addNotificationsToQueue` method in the `notificationService` includes comprehensive error handling, logging errors, and managing the state of the queue processing.
🔇 Additional comments (14)
apps/api/src/modules/providers/smtp/smtp.service.ts (2)

11-11: LGTM! Logger initialization follows NestJS best practices.

The default logger initialization with class name improves log filtering and debugging capabilities.


Line range hint 14-27: Consider masking sensitive information in logs.

The SMTP configuration contains sensitive credentials. While the current implementation doesn't explicitly log these values, it's worth adding a precautionary note.

Run this script to check for potential credential logging:

✅ Verification successful

Current logging implementation is secure

The code only logs operational status messages at debug level and does not expose any sensitive SMTP configuration data. The existing implementation already follows security best practices for logging.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for potential credential logging
rg -i "password|credentials|secret" -C 3 "logger\.(debug|log|info|warn|error)"

Length of output: 156


Script:

#!/bin/bash
# Search for potential credential logging with fixed patterns
echo "=== Searching for general credential logging ==="
rg -i "(password|credential|secret|auth)" --type ts -C 3 "\.(?:debug|log|info|warn|error)\("

echo -e "\n=== Searching for SMTP-specific logging ==="
rg -i "smtp" --type ts -C 3 "\.(?:debug|log|info|warn|error)\("

echo -e "\n=== Searching for config/transport logging ==="
rg -i "(config|transport)" --type ts -C 3 "\.(?:debug|log|info|warn|error)\("

Length of output: 779


Script:

#!/bin/bash
# Search in the SMTP service directory
echo "=== Searching for logger usage in SMTP service ==="
cd apps/api/src/modules/providers/smtp
rg "logger" -A 3 -B 3 --type ts

echo -e "\n=== Searching for config logging ==="
rg "smtpConfig" -A 3 -B 3 --type ts

echo -e "\n=== Checking all TypeScript files in SMTP directory ==="
find . -type f -name "*.ts" -exec cat {} \;

Length of output: 4106

apps/api/src/modules/providers/push-sns/push-sns.service.ts (2)

16-16: LGTM! Consistent with the standardized logger initialization pattern.

The implementation aligns with the project-wide logger injection improvements.


Line range hint 20-29: Review AWS credential handling in logs.

Similar to SMTP service, ensure AWS credentials are never logged, even in debug mode.

Run this script to verify credential handling:

✅ Verification successful

AWS credentials are properly handled in logs

The code follows secure practices with no credential logging. Debug logs only contain operational status messages without exposing sensitive information:

  • "Started assigning SNS push notification client"
  • "Sending SNS push notification"
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for AWS credential logging
rg -i "aws.*key|credentials|secret" -C 3 "logger\.(debug|log|info|warn|error)"

Length of output: 156


Script:

#!/bin/bash
# Search for potential AWS credential logging patterns
rg -t ts -t js "logger\." -C 3 | rg -i "aws.*key|credentials|secret"

# Additional specific search for AWS credential related logging
rg -t ts -t js -C 3 'this\.logger\.(debug|log|info|warn|error).*(\baws\b|\bcredentials\b|\bsecret\b|\baccessKey\b)'

Length of output: 188


Script:

#!/bin/bash
# Find and show the push-sns service file content
fd -t f "push-sns.service.ts" -x cat {}

# Search for all logger usage in TypeScript files containing 'sns'
rg -t ts "this\.logger\." -C 3 $(fd -t f "sns.*\.ts$")

Length of output: 5426

apps/api/src/modules/providers/sms-sns/sms-sns.service.ts (1)

16-16: LGTM! Logger initialization is consistent with other services.

The implementation maintains consistency across the codebase.

apps/api/src/modules/notifications/notifications.controller.ts (2)

12-12: LGTM! Logger initialization follows the standardized pattern.

The implementation aligns with the project-wide logger improvements.


Line range hint 38-43: Good error handling with detailed logging!

The error handling follows best practices by:

  1. Preserving HttpException
  2. Logging detailed error information
  3. Including stack trace for debugging
apps/api/src/modules/providers/sms-kapsystem/sms-kapsystem.service.ts (1)

37-37: LGTM! Consider documenting testing implications.

The logger initialization with class name context improves log filtering. However, this change might affect unit tests that need to verify logging behavior.

For testing scenarios where log verification is needed, you can still override the logger:

const mockLogger = new Logger();
const service = new SmsKapsystemService(httpService, providersService, mockLogger);
apps/api/src/modules/providers/sms-twilio/sms-twilio.service.ts (1)

39-39: LGTM! Consistent with logger injection pattern.

The implementation follows the same pattern as other services, maintaining consistency across the codebase.

apps/api/src/modules/providers/wa-twilio/wa-twilio.service.ts (1)

39-39: LGTM! Consider updating tests if needed.

The default logger initialization improves code consistency. Ensure any existing tests that explicitly pass a logger instance are updated accordingly.

Run this script to check for affected tests:

✅ Verification successful

No test impact found, but consider adding tests

The logger initialization change is safe as there are no existing tests that could be affected. However, since no tests were found for the WaTwilioService, consider adding unit tests to improve coverage.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for test files that might need updates
rg -l "new WaTwilioService.*Logger" --type ts

Length of output: 47


Script:

#!/bin/bash
# Find test files related to WaTwilioService
echo "=== Searching for WaTwilioService test files ==="
rg -l "WaTwilioService" --type ts | grep -i "test\|spec"

echo -e "\n=== Checking service instantiation in tests ==="
rg "new WaTwilioService" -A 5 -B 5 --type ts

echo -e "\n=== Checking for any mock/stub usage ==="
rg "WaTwilioService" -A 3 -B 3 --type ts | grep -i "mock\|stub\|test"

Length of output: 488


Script:

#!/bin/bash
# Search for any Twilio-related test files
echo "=== Searching for Twilio-related test files ==="
fd -t f "test|spec" | rg -l "twilio" -i

echo -e "\n=== Checking test directory structure ==="
fd -t d "test|spec|__tests__"

Length of output: 298

apps/api/src/modules/providers/sms-plivo/sms-plivo.service.ts (1)

55-55: LGTM! Logger initialization is consistent with other services.

The default logger initialization using the class name improves code consistency.

apps/api/src/modules/providers/mailgun/mailgun.service.ts (1)

24-24: LGTM! Logger initialization is consistent.

The default logger initialization using the class name improves code consistency.

apps/api/src/common/guards/api-key/api-key.guard.ts (1)

21-21: LGTM! Logger initialization is consistent.

The default logger initialization using the class name improves code consistency.

apps/api/src/modules/providers/aws-ses/aws-ses.service.ts (1)

29-29: LGTM! Well-structured logging implementation.

The logger initialization change is consistent with the PR objectives. The class demonstrates good logging practices with debug logs for tracking execution flow and error logs for exception cases.

@osm-vishnukyatannawar osm-vishnukyatannawar merged commit 028f66f into main Jan 21, 2025
6 checks passed
@osm-vishnukyatannawar osm-vishnukyatannawar deleted the feat/improve-logger-injection branch January 21, 2025 13:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants