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

rest-api(fix): Denest keys for logs #3230

Merged
merged 2 commits into from
Oct 4, 2024
Merged

Conversation

abtestingalpha
Copy link
Collaborator

@abtestingalpha abtestingalpha commented Oct 4, 2024

Summary by CodeRabbit

  • Bug Fixes

    • Improved logging functionality for incoming requests and outgoing responses, enhancing message structure and consistency.
    • Implemented conditional truncation of response body logs based on specific request paths.
  • New Features

    • Introduced a custom format function for logging, enabling more flexible handling of log messages.

Copy link
Contributor

coderabbitai bot commented Oct 4, 2024

Walkthrough

The changes in this pull request focus on enhancing the logging functionality within an Express application. The log message structure for incoming requests and outgoing responses has been updated to use an object format, encapsulating messages within an object that includes a msg property. Additionally, the outgoing response logging now conditionally truncates the response body based on the request path. A modification in the logger configuration allows for more flexible logging of objects, ensuring that the msg property is utilized effectively.

Changes

File Change Summary
packages/rest-api/src/app.ts Updated log message format for incoming requests and outgoing responses to use object format.
packages/rest-api/src/middleware/logger.ts Added custom format function to logger to handle object messages and ensure msg property is used.

Possibly related PRs

Suggested labels

size/m

Suggested reviewers

  • bigboydiamonds
  • trajan0x
  • ChiTimesChi
  • Defi-Moses

Poem

In the logs where data flows,
A rabbit hops where structure grows.
With messages wrapped in a cozy nest,
Each log now shines, a clearer quest!
Truncated tales for paths so bright,
Our logging's changed, oh what a sight! 🐇✨


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 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.

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

cloudflare-workers-and-pages bot commented Oct 4, 2024

Deploying sanguine-fe with  Cloudflare Pages  Cloudflare Pages

Latest commit: 5a6297f
Status: ✅  Deploy successful!
Preview URL: https://886d1e2f.sanguine-fe.pages.dev
Branch Preview URL: https://rest-api-denest-keys.sanguine-fe.pages.dev

View logs

Copy link

Deploying sanguine-fe with  Cloudflare Pages  Cloudflare Pages

Latest commit: b1db615
Status: ✅  Deploy successful!
Preview URL: https://90fcc8c8.sanguine-fe.pages.dev
Branch Preview URL: https://rest-api-denest-keys.sanguine-fe.pages.dev

View logs

Copy link
Contributor

@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 and nitpick comments (2)
packages/rest-api/src/app.ts (2)

Line range hint 14-20: Improved logging structure for incoming requests.

The change to an object-based logging format is a good improvement. It provides better structure and makes the logs easier to parse programmatically. The conditional inclusion of the request body for POST and PUT methods is also a good practice for data privacy.

Consider adding a headers field to the log object, excluding any sensitive information. This could provide valuable debugging information without compromising security. For example:

headers: Object.entries(req.headers).reduce((acc, [key, value]) => {
  if (!['authorization', 'cookie'].includes(key.toLowerCase())) {
    acc[key] = value;
  }
  return acc;
}, {}),

This would log all headers except for 'authorization' and 'cookie'.


Line range hint 26-34: Enhanced logging structure for outgoing responses with size management.

The change to an object-based logging format for outgoing responses is a good improvement, providing consistency with the incoming request logs and better structure for parsing. The conditional truncation of the response body is a smart approach to manage log size for potentially large responses.

Consider the following improvements:

  1. Instead of hardcoding the paths for truncation, create a configurable list of paths or a function to determine if a path should be truncated. This will make it easier to maintain as new routes are added. For example:
const shouldTruncateBody = (path: string) => {
  const truncatePaths = ['/', '/tokenlist'];
  return truncatePaths.some(p => path.toLowerCase().startsWith(p.toLowerCase()));
};

// Then in the logging code:
body: shouldTruncateBody(originalPath) ? '[truncated for size]' : body,
  1. To enhance security, consider implementing a function to sanitize the response body before logging, removing or masking sensitive information. This could be applied to all non-truncated responses:
const sanitizeBody = (body: any) => {
  // Implement logic to remove or mask sensitive fields
  // This is a simple example and should be adapted to your specific needs
  const sanitized = { ...body };
  if (sanitized.password) sanitized.password = '[REDACTED]';
  if (sanitized.token) sanitized.token = '[REDACTED]';
  return sanitized;
};

// Then in the logging code:
body: shouldTruncateBody(originalPath) ? '[truncated for size]' : sanitizeBody(body),

These changes will make the logging more flexible and secure as your API evolves.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between caccd1b and 5a6297f.

📒 Files selected for processing (2)
  • packages/rest-api/src/app.ts (2 hunks)
  • packages/rest-api/src/middleware/logger.ts (1 hunks)
🧰 Additional context used
🪛 Biome
packages/rest-api/src/middleware/logger.ts

[error] 28-28: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

🔇 Additional comments (1)
packages/rest-api/src/middleware/logger.ts (1)

23-30: 🛠️ Refactor suggestion

Refactor the logger format function for improved robustness

The new format function successfully denests keys for logs, which aligns with the PR objective. However, there are a few areas where we can improve the implementation:

  1. Instead of modifying the info object directly, consider creating a new object to avoid potential side effects.
  2. Use a deep merge function instead of Object.assign to handle nested objects correctly.
  3. Consider keeping the original message property, as other format functions might expect it.

Here's a suggested refactoring:

winston.format((info) => {
  const result = { ...info };
  if (typeof info.message === 'object') {
    result = deepMerge(result, info.message);
  }
  result.msg = result.msg || result.message;
  return result;
})(),

This approach preserves the original object, handles nested objects correctly, and keeps the message property intact.

To ensure this change doesn't break existing logging behavior, we should verify how the logger is used throughout the codebase. Run the following script:

Regarding the static analysis hint about using the delete operator: While it's generally good to avoid delete for performance reasons, in this logging context, the performance impact is negligible. However, our refactored version addresses this concern by not using delete at all.

✅ Verification successful

Logger usage verified and refactoring is safe

The proposed refactoring of the logger format function has been reviewed against the codebase. Extensive usage of the logger across various modules was analyzed, and no conflicts or issues were found that would impede the suggested changes.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for logger usage in the codebase
rg --type typescript 'logger\.' -A 3 -B 1

Length of output: 78


Script:

#!/bin/bash
# Search for logger usage in TypeScript files
rg 'logger\.' --glob '*.ts' --glob '*.tsx' -A 3 -B 1

Length of output: 11725

🧰 Tools
🪛 Biome

[error] 28-28: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

Copy link

codecov bot commented Oct 4, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Please upload report for BASE (master@caccd1b). Learn more about missing BASE report.
Report is 2 commits behind head on master.

Additional details and impacted files
@@             Coverage Diff              @@
##             master       #3230   +/-   ##
============================================
  Coverage          ?   90.43902%           
============================================
  Files             ?          54           
  Lines             ?        1025           
  Branches          ?          82           
============================================
  Hits              ?         927           
  Misses            ?          95           
  Partials          ?           3           
Flag Coverage Δ
packages 90.43902% <ø> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link

codecov bot commented Oct 4, 2024

Bundle Report

Bundle size has no change ✅

@abtestingalpha abtestingalpha merged commit 7a0c7e7 into master Oct 4, 2024
37 checks passed
@abtestingalpha abtestingalpha deleted the rest-api/denest-keys branch October 4, 2024 16:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant