Skip to content

Comments

Extend logger functionality#331

Merged
elie222 merged 3 commits intomainfrom
extended-logger
Feb 10, 2025
Merged

Extend logger functionality#331
elie222 merged 3 commits intomainfrom
extended-logger

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Feb 10, 2025

Summary by CodeRabbit

  • New Features

    • Enhanced logging now provides enriched context in system alerts and error notifications, leading to more transparent and actionable monitoring.
  • Refactor

    • Streamlined logging for outbound communications improves clarity in error tracking and simplifies troubleshooting, contributing to a more reliable experience.
    • Improved logging mechanism in inbound processing for better contextual information and error handling.

@vercel
Copy link

vercel bot commented Feb 10, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Updated (UTC)
inbox-zero ✅ Ready (Inspect) Visit Preview Feb 10, 2025 7:13pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 10, 2025

Warning

Rate limit exceeded

@elie222 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 23 minutes and 43 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 828c09e and 303958c.

📒 Files selected for processing (2)
  • apps/web/utils/ai/choose-rule/execute.ts (3 hunks)
  • apps/web/utils/reply-tracker/inbound.ts (1 hunks)

Walkthrough

This update enhances the logging functionality by introducing a new exported Logger type and extending the createScopedLogger function with an internal createLogger that accepts optional fields. Additionally, log formatting is modified to concatenate extra context fields with existing arguments. The changes also update the reply tracker module to instantiate and use the enhanced logger with contextual properties for better error and info logging.

Changes

File(s) Summary
apps/web/utils/logger.ts Added exported Logger type. Modified createScopedLogger to include an internal createLogger accepting an optional fields parameter, updated formatMessage to combine fields and arguments, and added a with method for creating scoped logger instances. Adjusted createAxiomLogger to support additional fields.
apps/web/utils/reply-tracker/outbound.ts Imported the new Logger type. Modified logger instantiation in handleOutboundReply to include additional context fields and simplified error logging. Updated createReplyTrackerOutbound to receive the logger as a parameter and directly log error reasons.
apps/web/utils/reply-tracker/inbound.ts Removed the original logger instance and created a new logger within markNeedsReply using createScopedLogger. Updated error logging to utilize the new logger instance and integrated contextual information directly into logger calls.

Sequence Diagram(s)

sequenceDiagram
    participant Caller as Call Site
    participant Logger as Logger Module
    participant Formatter as formatMessage

    Caller->>Logger: createScopedLogger(context)
    Logger->>Logger: createLogger(optional fields)
    Logger->>Formatter: formatMessage(fields, args)
    Formatter-->>Logger: Formatted message
    Logger-->>Caller: Logger instance with "with" method
Loading
sequenceDiagram
    participant Service as Reply Tracker Service
    participant Logger as Enhanced Logger
    participant DB as Database/Label Service

    Service->>Logger: Instantiate logger with context (email, userId, etc.)
    alt Error encountered
        Service->>Logger: Log error ("No thread messages found" / error reason)
    else Tracker created
        Service->>Logger: Log info ("Reply needed")
    end
    Service->>DB: Perform upsert/labeling operations with logging
Loading

Possibly related PRs

Poem

I'm a rabbit with ears so keen,
Hopping through logs in every scene.
Extra fields now join the rhyme,
Keeping track in record time.
With a hop and cheerful glee,
Debugging's fun—so feel free!
🐇✨


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

🧹 Nitpick comments (4)
apps/web/utils/logger.ts (2)

20-42: Consider adding type safety for the fields object.

The implementation looks good, but we could improve type safety for the fields object.

Consider this improvement:

- const createLogger = (fields: Record<string, unknown> = {}) => {
+ type LogFields = Record<string, string | number | boolean | null | undefined>;
+ const createLogger = (fields: LogFields = {}) => {

This would prevent accidentally passing complex objects that might not serialize well.


44-59: Consider adding return type annotation for better type inference.

The logger implementation looks good, but adding explicit return type would improve maintainability.

Consider adding return type:

- return {
+ type LoggerReturn = {
+   info: (message: string, ...args: unknown[]) => void;
+   error: (message: string, ...args: unknown[]) => void;
+   warn: (message: string, ...args: unknown[]) => void;
+   trace: (message: string, ...args: unknown[]) => void;
+   with: (newFields: LogFields) => LoggerReturn;
+ };
+ return {
apps/web/utils/reply-tracker/outbound.ts (2)

51-51: Consider adding error context for better debugging.

While the error message is clear, adding more context would help with debugging.

- logger.error("No thread messages found");
+ logger.error("No thread messages found", { enabled, hasLabels: !!awaitingReplyLabelId });

133-143: Consider consolidating error handling.

The error handling for upsert and label operations is duplicated.

Consider consolidating the error handling:

- if (upsertResult.status === "rejected") {
-   logger.error("Failed to upsert reply tracker", {
-     error: upsertResult.reason,
-   });
- }
- 
- if (labelResult.status === "rejected") {
-   logger.error("Failed to label reply tracker", {
-     error: labelResult.reason,
-   });
- }
+ const errors: Record<string, unknown> = {};
+ if (upsertResult.status === "rejected") errors.upsert = upsertResult.reason;
+ if (labelResult.status === "rejected") errors.label = labelResult.reason;
+ if (Object.keys(errors).length > 0) {
+   logger.error("Failed to create reply tracker", { errors });
+ }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8149fed and b1d406f.

📒 Files selected for processing (2)
  • apps/web/utils/logger.ts (2 hunks)
  • apps/web/utils/reply-tracker/outbound.ts (4 hunks)
🔇 Additional comments (3)
apps/web/utils/logger.ts (2)

5-5: LGTM! Good practice exporting the logger type.

Exporting the logger type allows for proper type checking when using the logger in other files.


64-82: Ensure consistent error handling between development and production environments.

The Axiom logger implementation looks good, but there's a potential inconsistency in error handling between environments.

The trace method only logs in non-production environments. Verify if this is intentional and if there should be any fallback behavior in production.

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Search for other trace logging patterns in the codebase
rg "trace.*production" --type ts

Length of output: 34


Logging Behavior in Production is Intentional

After verifying the code and searching the codebase, it appears that the implementation of the trace method—logging only in non-production environments—is intentional. No fallback behavior for production was found, and the rest of the logger methods (info, error, warn) function uniformly in all environments. Disabling trace logs in production is a common practice to reduce noise and performance overhead.

apps/web/utils/reply-tracker/outbound.ts (1)

43-48: LGTM! Good use of structured logging context.

The logger initialization with context fields provides good traceability.

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

🧹 Nitpick comments (1)
apps/web/utils/reply-tracker/inbound.ts (1)

67-92: Consider adding success logging for better observability.

While error cases are well-logged, adding success logs would provide better visibility into the system's normal operation. This could help with monitoring and debugging by establishing a complete picture of the operation flow.

  const [dbResult, removeLabelResult, newLabelResult] =
    await Promise.allSettled([dbPromise, removeLabelPromise, newLabelPromise]);

  const logger = createScopedLogger("reply-tracker/inbound").with({
    userId,
    threadId,
    messageId,
  });

+ if (dbResult.status === "fulfilled") {
+   logger.info("Successfully marked needs reply in database");
+ }
  if (dbResult.status === "rejected") {
    logger.error("Failed to mark needs reply", {
      error: dbResult.reason,
    });
  }

+ if (removeLabelResult.status === "fulfilled") {
+   logger.info("Successfully removed awaiting reply label");
+ }
  if (removeLabelResult.status === "rejected") {
    logger.error("Failed to remove awaiting reply label", {
      error: removeLabelResult.reason,
    });
  }

+ if (newLabelResult.status === "fulfilled") {
+   logger.info("Successfully added needs reply label");
+ }
  if (newLabelResult.status === "rejected") {
    logger.error("Failed to label needs reply", {
      error: newLabelResult.reason,
    });
  }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b1d406f and 828c09e.

📒 Files selected for processing (2)
  • apps/web/utils/reply-tracker/inbound.ts (1 hunks)
  • apps/web/utils/reply-tracker/outbound.ts (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/web/utils/reply-tracker/outbound.ts
🔇 Additional comments (1)
apps/web/utils/reply-tracker/inbound.ts (1)

70-74: LGTM! Well-structured logging setup.

The logger creation with scoped context is well-implemented. The inclusion of relevant tracking IDs (userId, threadId, messageId) will make debugging and monitoring more effective.

@elie222 elie222 merged commit 4b5ea22 into main Feb 10, 2025
3 of 4 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Jul 30, 2025
@coderabbitai coderabbitai bot mentioned this pull request Sep 22, 2025
@coderabbitai coderabbitai bot mentioned this pull request Oct 15, 2025
This was referenced Oct 31, 2025
@coderabbitai coderabbitai bot mentioned this pull request Nov 24, 2025
This was referenced Dec 13, 2025
@elie222 elie222 deleted the extended-logger branch December 18, 2025 23:01
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.

1 participant