Skip to content

Improve coordinator logs and extend structured logger #1389

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 12 commits into from
Oct 9, 2024

Conversation

nicktrn
Copy link
Collaborator

@nicktrn nicktrn commented Oct 8, 2024

  • Convert all coordinator logs into structured format
  • Socket handlers can conditionally log full payloads
  • Improve structured logger API for additional fields

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced structured logging across various components, enhancing log clarity and context.
    • Added options for logging handler payloads in the ZodNamespace and ZodSocket implementations.
  • Improvements

    • Enhanced error logging to provide more context.
    • Updated logging mechanisms in the Checkpointer, Exec, Buildah, and Crictl classes for better data handling.
    • Refined control flow and logging in the TaskCoordinator class and HTTP server.
    • Adjusted default behavior for checkpoint simulation in the Docker provider.

These changes collectively improve the robustness and maintainability of the logging framework in the application.

Copy link

changeset-bot bot commented Oct 8, 2024

🦋 Changeset detected

Latest commit: fc25131

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 9 packages
Name Type
@trigger.dev/core Patch
@trigger.dev/build Patch
trigger.dev Patch
@trigger.dev/sdk Patch
@internal/redis-worker Patch
@internal/zod-worker Patch
@trigger.dev/database Patch
@trigger.dev/otlp-importer Patch
@internal/testcontainers Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Copy link
Contributor

coderabbitai bot commented Oct 8, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The changes in this pull request focus on enhancing the structured logging capabilities within the @trigger.dev/core package and related components. Key modifications include replacing instances of SimpleLogger with SimpleStructuredLogger across various classes, improving how logs are formatted and contextualized. Additional updates involve refining error logging, introducing new properties for payload logging in the ZodSocket implementation, and adjusting the logging structure in several classes to support these enhancements.

Changes

File Path Change Summary
.changeset/proud-yaks-thank.md Summary of changes related to structured logging improvements and the transition from SimpleLogger to SimpleStructuredLogger.
apps/coordinator/src/checkpointer.ts Replaced SimpleLogger with SimpleStructuredLogger, updated error logging to use structured format, and adjusted logging messages for consistency.
apps/coordinator/src/cleaner.ts Transitioned TempFileCleaner to use SimpleStructuredLogger, updated logging messages for clarity, and modified error logging to utilize structured objects.
apps/coordinator/src/exec.ts Replaced SimpleLogger with SimpleStructuredLogger in Exec, Buildah, and Crictl classes, updated logging methods to reflect structured logging format.
apps/coordinator/src/index.ts Updated to use SimpleStructuredLogger, added exitRun function for centralized exit logic, and refined logging in HTTP server and socket event handlers.
apps/docker-provider/src/index.ts Changed default value of FORCE_CHECKPOINT_SIMULATION from "true" to "false", affecting checkpointing logic in DockerTaskOperations.
packages/core/src/v3/utils/structuredLogger.ts Added addFields method to SimpleStructuredLogger, modified logged object structure, and adjusted property handling in logging methods.
packages/core/src/v3/zodNamespace.ts Introduced optional logHandlerPayloads property in ZodNamespaceOptions interface for payload logging configuration.
packages/core/src/v3/zodSocket.ts Added logPayloads property to ZodSocketMessageHandlerOptions, updated logging practices in message handling, and included new logging options in connection settings.

Possibly related PRs

Suggested reviewers

  • ericallam
  • matt-aitken

Poem

🐰 In the logs where bunnies hop,
Structured tales, we’ll never stop!
With fields and context, clear and bright,
Our logging dance is pure delight!
So let us cheer, with hops and glee,
For better logs, come join with me! 🌟


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.

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.

@nicktrn nicktrn changed the title Improve coordinator logging and extend structured logger Improve coordinator logs and extend structured logger Oct 8, 2024
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: 5

🧹 Outside diff range and nitpick comments (9)
.changeset/proud-yaks-thank.md (1)

1-5: LGTM! Consider adding more details to the description.

The changeset file is correctly formatted and appropriately marks this as a patch update. The description aligns with the PR objectives and summary.

To provide more context for future reference, consider expanding the description slightly. For example:

-Improvements to structured logger and conditional payload logging
+Improvements to structured logger and conditional payload logging:
+- Enhanced structured logging capabilities
+- Introduced conditional logging of full payloads in socket handlers
+- Extended structured logger API to support additional fields
packages/core/src/v3/utils/structuredLogger.ts (1)

78-82: LGTM: Improved log structure with a minor suggestion

The changes to the #structuredLog method enhance the structure of the logged object:

  1. Prefixing name and level with $ helps distinguish them as metadata fields.
  2. Placing timestamp first in the log object is a good practice for chronological sorting.
  3. The modification to args spreading handles the single argument case more explicitly.

These improvements align well with the PR objective of enhancing coordinator logging.

Consider adding a comment explaining the significance of the $ prefix for $name and $level. This would improve code readability and maintain consistency if this convention is used elsewhere. For example:

const structuredLog = {
  timestamp: new Date(),
  // Prefix metadata fields with $ for distinction
  $name: this.name,
  message,
  $level: level,
  ...(args.length === 1 ? args[0] : args),
  ...this.fields,
};
packages/core/src/v3/zodNamespace.ts (1)

44-44: LGTM! Consider adding documentation for the new property.

The addition of the logHandlerPayloads property to the ZodNamespaceOptions interface and its usage in the constructor are correct and align with the PR objectives. This change allows for conditional logging of handler payloads, which can be useful for debugging and monitoring purposes.

Consider adding a brief comment above the logHandlerPayloads property in the interface to explain its purpose and impact. For example:

/**
 * When set to true, enables logging of handler payloads.
 * This can be useful for debugging but may increase log verbosity.
 */
logHandlerPayloads?: boolean;

This documentation will help other developers understand the purpose and implications of using this option.

Also applies to: 100-100

packages/core/src/v3/zodSocket.ts (3)

71-71: LGTM! Consider adding JSDoc comment for clarity.

The addition of the logPayloads option is a good improvement for configurable logging. It allows users to control whether payloads are logged, which can be crucial for debugging and security purposes.

Consider adding a JSDoc comment to explain the purpose and impact of this option:

/** 
 * If true, log full payloads of incoming messages. 
 * Use with caution as it may log sensitive information.
 */
logPayloads?: boolean;

103-103: LGTM! Consider simplifying the boolean conversion.

The initialization of #logPayloads is well-implemented, providing multiple levels of configuration. The use of an environment variable as a fallback is a good practice.

For clarity, you might consider simplifying the boolean conversion:

this.#logPayloads = options.logPayloads ?? (process.env.LOG_SOCKET_HANDLER_PAYLOADS === 'true') ?? false;

This explicitly checks for the string 'true', which might be clearer than relying on truthy/falsy conversion of environment variable strings.


200-202: LGTM! Good implementation of conditional logging.

The addition of conditional logging based on #logPayloads is a good improvement. It allows for more granular control over logging potentially sensitive information.

For clarity, you might consider extracting the logging logic into a separate method:

private logIncomingEvent(eventName: string, message: any, hasCallback: boolean) {
  const logData = {
    eventName,
    ...(this.#logPayloads ? { eventMessage: message } : {}),
    hasCallback,
  };
  this.#logger.info(`Incoming event ${eventName}`, logData);
}

Then call this method in registerHandlers:

this.logIncomingEvent(eventName, message, !!callback);

This would make the registerHandlers method cleaner and easier to read.

apps/coordinator/src/exec.ts (1)

Line range hint 122-122: Typo in log message

There's a typographical error in the log message: "initiaized" should be "initialized".

Apply this diff to correct the typo:

-    this.logger.log("initiaized", { opts });
+    this.logger.log("initialized", { opts });
apps/coordinator/src/index.ts (2)

395-397: Avoid Variable Shadowing by Renaming the Local logger Variable

The logger variable is redefined within the onConnection method, which can cause confusion due to shadowing the module-level logger. To improve clarity, consider renaming the local variable to something like connectionLogger or socketLogger.

Apply this change:

-const logger = new SimpleStructuredLogger("prod-worker", undefined, {
+const connectionLogger = new SimpleStructuredLogger("prod-worker", undefined, {
  socketId: socket.id,
});

And update references within the method accordingly.


146-146: Ensure Consistent Logging and Error Handling for Missing Sockets

The logging statements for missing sockets use different log levels and messages:

  • Line 146: log.debug("Socket for attempt not found");
  • Line 238 & 258: logger.log("Socket for attempt/run not found", { ... });

To maintain consistency and proper log level usage, consider standardizing these statements. If the absence of a socket is an unexpected condition, using log.warn or log.error might be more appropriate.

Suggested change:

-log.debug("Socket for attempt not found");
+log.warn("Socket for attempt not found");

And similarly for other instances.

Also applies to: 238-238, 258-258

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 07f82ea and 47dbf90.

📒 Files selected for processing (8)
  • .changeset/proud-yaks-thank.md (1 hunks)
  • apps/coordinator/src/checkpointer.ts (3 hunks)
  • apps/coordinator/src/exec.ts (4 hunks)
  • apps/coordinator/src/index.ts (21 hunks)
  • apps/docker-provider/src/index.ts (1 hunks)
  • packages/core/src/v3/utils/structuredLogger.ts (1 hunks)
  • packages/core/src/v3/zodNamespace.ts (2 hunks)
  • packages/core/src/v3/zodSocket.ts (7 hunks)
🧰 Additional context used
🔇 Additional comments (16)
packages/core/src/v3/utils/structuredLogger.ts (1)

63-68: LGTM: New addFields method enhances logger flexibility

The addition of the addFields method is a valuable enhancement to the SimpleStructuredLogger class. It allows for dynamic addition of fields to the logger, which aligns well with the PR objective of extending the structured logger API. The implementation is clean and correctly merges new fields with existing ones.

apps/docker-provider/src/index.ts (1)

23-23: Approve change with verification suggestion.

The modification to set the default value of FORCE_CHECKPOINT_SIMULATION to "false" is a good change. It aligns with the PR objectives by allowing for more realistic behavior by default, potentially improving the accuracy of logs and system behavior.

However, this change may significantly impact the system's operation, particularly in environments where the FORCE_CHECKPOINT_SIMULATION environment variable is not explicitly set.

To ensure this change doesn't introduce unexpected behavior, please:

  1. Verify that all environments where this code will be deployed have the FORCE_CHECKPOINT_SIMULATION environment variable explicitly set if simulation mode is required.
  2. Test the system thoroughly with this new default to ensure it behaves correctly when using actual checkpointing instead of simulation.
  3. Monitor the system's performance after deployment, as increased usage of actual checkpointing might have performance implications.
packages/core/src/v3/zodSocket.ts (3)

96-96: LGTM! Good use of private field.

The addition of the #logPayloads private field is a good implementation detail. It appropriately encapsulates the logging configuration within the class.


126-126: LGTM! Improved error logging.

The switch from console.error to the structured logger is a good improvement. It enhances consistency in logging practices and allows for better integration with logging systems.


Line range hint 1-458: Overall, excellent improvements to logging capabilities.

The changes in this file significantly enhance the logging system of the ZodSocket implementation. The addition of configurable payload logging and the use of structured logging throughout improve both flexibility and consistency. The changes are well-implemented and consider security aspects by making payload logging optional.

A few minor suggestions have been made for further improvements:

  1. Adding JSDoc comments for new options
  2. Simplifying boolean conversions
  3. Extracting some logging logic into separate methods

These suggestions are minor and don't detract from the overall quality of the changes. Great work on improving the logging capabilities!

apps/coordinator/src/checkpointer.ts (4)

11-11: LGTM: Import of SimpleStructuredLogger added

The addition of SimpleStructuredLogger import aligns with the PR objective of improving structured logging capabilities.


90-90: LGTM: Logger updated to use SimpleStructuredLogger

The #logger property is correctly updated to use SimpleStructuredLogger with a more descriptive name "checkpointer". This change aligns with the PR objective of converting coordinator logs to a structured format.


141-141: LGTM: Error logging updated to use structured format

The error logging in the init method has been updated to pass an object containing the error, which aligns with the structured logging approach. This change enhances the error information captured in the logs.


Line range hint 1-624: Overall assessment: Structured logging successfully implemented

The changes in this file successfully implement structured logging in the Checkpointer class, aligning with the PR objectives. The modifications include:

  1. Importing the SimpleStructuredLogger
  2. Updating the logger initialization
  3. Adjusting the error logging format

These changes will improve the clarity and usability of log data from the Checkpointer class.

apps/coordinator/src/exec.ts (7)

1-1: Import SimpleStructuredLogger

The addition of SimpleStructuredLogger import ensures that structured logging capabilities are available throughout the file.


21-21: Update logger type in ExecOptions interface

The logger property in ExecOptions has been updated to SimpleStructuredLogger. Please verify that all implementations of ExecOptions are updated to pass a SimpleStructuredLogger instance to prevent type conflicts.


29-29: Update logger property in Exec class

The logger property in the Exec class is now SimpleStructuredLogger, aligning with the structured logging enhancement.


37-37: Initialize logger with SimpleStructuredLogger in Exec

The logger is correctly initialized with SimpleStructuredLogger, providing a default identifier of "exec" when no logger is supplied.


106-106: Update logger property in Buildah class

The logger property in the Buildah class has been updated to SimpleStructuredLogger, enhancing logging consistency.


223-223: Update logger property in Crictl class

The logger property in the Crictl class is now SimpleStructuredLogger, aligning it with the structured logging updates.


Line range hint 238-238: Typo in log message

There's a typographical error in the log message: "initiaized" should be "initialized".

Apply this diff to correct the typo:

-    this.logger.log("initiaized", { opts });
+    this.logger.log("initialized", { opts });

Copy link

pkg-pr-new bot commented Oct 8, 2024

pnpm add https://pkg.pr.new/triggerdotdev/trigger.dev/@trigger.dev/build@1389
pnpm add https://pkg.pr.new/triggerdotdev/trigger.dev@1389
pnpm add https://pkg.pr.new/triggerdotdev/trigger.dev/@trigger.dev/core@1389
pnpm add https://pkg.pr.new/triggerdotdev/trigger.dev/@trigger.dev/sdk@1389

commit: 2c716a9

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

🧹 Outside diff range and nitpick comments (1)
packages/core/src/v3/utils/structuredLogger.ts (1)

79-82: Approved: Improved structure and handling in #structuredLog

The changes to the #structuredLog method enhance the logging structure and improve argument handling:

  1. Renaming name and level to $name and $level helps avoid potential conflicts with user-defined fields.
  2. The new property order (timestamp, $name, $level, fields, args) is more logical and consistent.
  3. The modified args spreading (args.length === 1 ? args[0] : args) elegantly handles both single and multiple arguments.

These improvements align well with the PR objective of enhancing structured logging capabilities.

Consider extracting the args spreading logic into a separate variable for improved readability:

const argsObject = args.length === 1 ? args[0] : args;
const structuredLog = {
  timestamp: new Date(),
  $name: this.name,
  $level: level,
  ...this.fields,
  ...argsObject,
};

This minor refactoring would make the structuredLog object construction cleaner and more self-explanatory.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 47dbf90 and 2c716a9.

📒 Files selected for processing (6)
  • apps/coordinator/src/checkpointer.ts (3 hunks)
  • apps/coordinator/src/cleaner.ts (4 hunks)
  • apps/coordinator/src/index.ts (44 hunks)
  • packages/core/src/v3/utils/structuredLogger.ts (1 hunks)
  • packages/core/src/v3/zodNamespace.ts (2 hunks)
  • packages/core/src/v3/zodSocket.ts (8 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • apps/coordinator/src/checkpointer.ts
  • packages/core/src/v3/zodNamespace.ts
  • packages/core/src/v3/zodSocket.ts
🧰 Additional context used
📓 Learnings (1)
apps/coordinator/src/index.ts (1)
Learnt from: nicktrn
PR: triggerdotdev/trigger.dev#1389
File: apps/coordinator/src/index.ts:0-0
Timestamp: 2024-10-08T13:40:56.493Z
Learning: Currently, we are focusing on updating `SimpleLogger` to `SimpleStructuredLogger` only in the coordinator files.
🔇 Additional comments (8)
packages/core/src/v3/utils/structuredLogger.ts (2)

63-68: LGTM: New addFields method enhances logger flexibility

The new addFields method is a valuable addition to the SimpleStructuredLogger class. It allows for dynamic addition of fields to the logger instance, which aligns well with the PR objective of extending the structured logger capabilities. The implementation is concise and correctly merges new fields with existing ones.


Line range hint 1-87: Summary: Effective enhancements to structured logging capabilities

The changes made to the SimpleStructuredLogger class in this file successfully address the PR objectives of improving coordinator logs and extending the structured logger:

  1. The new addFields method allows for dynamic addition of fields, enhancing the logger's flexibility.
  2. Modifications to the #structuredLog method improve the structure of logged objects and handle arguments more effectively.

These enhancements will contribute to better clarity and usability of log data, as well as more detailed logging capabilities. The changes are well-implemented and align closely with the stated goals of the pull request.

apps/coordinator/src/index.ts (6)

6-6: Improved logging with SimpleStructuredLogger

The change from SimpleLogger to SimpleStructuredLogger aligns with the PR objective of enhancing structured logging. This will provide more detailed and easier-to-parse log outputs.

Also applies to: 20-20, 33-33


405-429: Improved logging and centralized exit logic

The initialization of a structured logger for each connection and the introduction of the exitRun function improve logging consistency and centralize the exit logic. This makes the code more maintainable and easier to debug.

Also applies to: 432-441


537-550: Enhanced event logging with structured format

The event handlers now use structured logging, which will greatly improve log readability and searchability. The use of the omit function to exclude sensitive or verbose fields is a good practice for managing log content.

Also applies to: 602-608, 683-694, 794-803, 818-824, 859-865, 931-937, 1011-1017, 1092-1098, 1122-1128, 1139-1145, 1170-1176, 1182-1188


Line range hint 559-570: Improved error handling and logging

Error handling has been enhanced with more contextual information in logs. This will significantly aid in debugging and troubleshooting issues in production.

Also applies to: 617-628, 646-650, 760-773, 888-901, 962-975, 1042-1055, 1114-1114, 1155-1155


1244-1244: Consistent logging in HTTP server

The HTTP server logging now uses the structured logging approach, maintaining consistency with the rest of the file. This unified approach will make log analysis more straightforward.

Also applies to: 1274-1274


Line range hint 1-1289: Overall improvement in logging and code structure

The changes in this file significantly enhance the logging capabilities by implementing structured logging throughout. This consistent approach will greatly improve debugging, monitoring, and analysis of the application's behavior. The code structure has also been improved, with centralized logic for certain operations like exiting runs. These changes align well with the PR objectives and should lead to better maintainability and observability of the system.

@nicktrn nicktrn merged commit bf15d8a into main Oct 9, 2024
4 of 7 checks passed
@nicktrn nicktrn deleted the coordinator-observability branch October 9, 2024 11:20
@coderabbitai coderabbitai bot mentioned this pull request Nov 19, 2024
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