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

chore: effect-log.PrettyLogger -> Effect.Logger.pretty #997

Merged
merged 10 commits into from
Oct 7, 2024

Conversation

juliusmarminge
Copy link
Collaborator

@juliusmarminge juliusmarminge commented Oct 6, 2024

  • Use built-in loggers (Effect added a pretty logger after we had initially added effect-log 3rd party lib.
  • Allow user to set format (e.g. json logger to integrate better with their log provider)

Examples

"Upload completed ..." log is a console.log from the user's file router

pretty (default in dev)

CleanShot 2024-10-06 at 14 01 58@2x

json (default in prod)

CleanShot 2024-10-06 at 14 01 30@2x

structured

CleanShot 2024-10-06 at 14 04 17@2x

logFmt

CleanShot 2024-10-06 at 14 05 04@2x

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced a new logFormat configuration option for enhanced logging customization.
    • Added detailed examples in the documentation for createUploadthing and createRouteHandler functions across various frameworks.
  • Bug Fixes

    • Refined error handling for POST requests, particularly regarding client version mismatches and missing file routes.
  • Refactor

    • Updated logging strategy in multiple components, improving the structure and readability of the code related to logging and layer management.
  • Chores

    • Removed unnecessary dependency from the package configuration.

Copy link

changeset-bot bot commented Oct 6, 2024

🦋 Changeset detected

Latest commit: e0893bf

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

This PR includes changesets to release 1 package
Name Type
uploadthing Minor

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

vercel bot commented Oct 6, 2024

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

Name Status Preview Comments Updated (UTC)
docs-uploadthing ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 7, 2024 9:23pm
1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
legacy-docs-uploadthing ⬜️ Skipped (Inspect) Oct 7, 2024 9:23pm

Copy link
Contributor

coderabbitai bot commented Oct 6, 2024

Walkthrough

The pull request involves modifications to the uploadthing package, specifically updating the package.json, handler.ts, index.ts, types.ts, and documentation files. Changes include adjustments to the exports paths in package.json, a refactor of the logging mechanism in handler.ts, and improvements to the layer management in the UTApi class in index.ts. Additionally, a new logFormat property has been introduced in various configurations and documentation, enhancing the logging capabilities. The overall functionality remains intact, focusing on enhancing clarity and structure without altering public method signatures.

Changes

File Path Change Summary
packages/uploadthing/package.json Updated exports paths from .d.cts to .d.cjs; removed effect-log dependency; version remains 7.0.2.
packages/uploadthing/src/internal/handler.ts Replaced PrettyLogger with withLogFormat; refined error handling and logging in various functions.
packages/uploadthing/src/sdk/index.ts Replaced PrettyLogger with withLogFormat; refactored executeAsync for improved layer management.
packages/uploadthing/src/sdk/types.ts Added logFormat property to UTApiOptions interface for configurable logging.
docs/src/app/(docs)/api-reference/server/page.mdx Updated documentation to include logFormat property with examples for server bindings.
docs/src/app/(docs)/api-reference/ut-api/page.mdx Added logFormat property details in UTApi SDK documentation.
examples/minimal-appdir/src/app/api/uploadthing/route.ts Added logFormat configuration to createRouteHandler function.
packages/uploadthing/src/internal/logger.ts Introduced LogFormat constant and withLogFormat function for dynamic logging configuration.
packages/uploadthing/src/internal/types.ts Updated RouteHandlerConfig type to include logFormat property for enhanced logging options.

Possibly related PRs

Suggested labels

@uploadthing/react

Suggested reviewers

  • markflorkowski

🐇 In the code, we hop and play,
With logs that shine both night and day.
The paths are changed, the errors refined,
A clearer way for all to find.
So let us cheer, with joy we sing,
For better code is a lovely thing! 🐇✨


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.

@vercel vercel bot temporarily deployed to Preview – legacy-docs-uploadthing October 6, 2024 11:24 Inactive
@github-actions github-actions bot removed the examples label Oct 6, 2024
@juliusmarminge juliusmarminge changed the title chore: effect-log.prettyLogger -> Effect.Logger.pretty chore: effect-log.PrettyLogger -> Effect.Logger.pretty Oct 6, 2024
Copy link

pkg-pr-new bot commented Oct 6, 2024

Copy link
Contributor

github-actions bot commented Oct 6, 2024

📦 Bundle size comparison

Bundle Size (gzip) Visualization
Main 26.04KB See Treemap 📊
PR (f8605d6) 26.04KB See Treemap 📊
Diff No change

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 (10)
.changeset/young-cars-tell.md (1)

1-7: LGTM! Changeset looks good with a minor suggestion.

The changeset correctly identifies this as a minor version update and provides a clear, concise description of the new feature. The inclusion of a link to the documentation is helpful.

Consider adding a brief example of how to use the new logFormat config option to make it even more user-friendly. For instance:

You can now set any of the [built-in log formats](https://effect.website/docs/guides/observability/logging#built-in-loggers) by passing in the `logFormat` config option. For example:

```typescript
import { createUploadthing } from "uploadthing/next";

const f = createUploadthing({
  logFormat: "pretty", // or "json", "structured", etc.
});

This addition would provide users with a quick start on how to implement the new feature.

</blockquote></details>
<details>
<summary>packages/uploadthing/src/sdk/types.ts (1)</summary><blockquote>

`35-40`: **LGTM: New `logFormat` property is well-defined and documented.**

The new `logFormat` property is correctly added to the `UTApiOptions` interface. It's optional, which maintains backward compatibility, and its type (`Config.Config.Success<typeof LogFormat>`) is consistent with the new imports.

The JSDoc comment provides useful information about the default behavior and links to further documentation. However, consider adding a brief explanation of what this property does to make it even more clear for users.



Consider updating the JSDoc comment to include a brief explanation of the property's purpose, for example:

```typescript
/**
 * Specifies the format for log entries.
 * @default "pretty" in development, else "json"
 * @see https://effect.website/docs/guides/observability/logging#built-in-loggers
 */
packages/uploadthing/src/internal/types.ts (1)

178-183: LGTM: Addition of logFormat property

The new logFormat property in RouteHandlerConfig is well-defined and aligns with the PR objective. The use of Effect's configuration system ensures type safety, and the optional nature maintains backward compatibility.

The JSDoc comment is informative, but consider adding a brief description of what the logFormat property does, in addition to its default values and link to documentation.

Consider updating the JSDoc comment to include a brief description of the property's purpose:

 /**
- * What format log entries should be in
+ * Specifies the format for log entries. This allows customization of log output for different environments.
  * @default "pretty" in development, else "json"
  * @see https://effect.website/docs/guides/observability/logging#built-in-loggers
  */
docs/src/app/(docs)/api-reference/server/page.mdx (1)

247-255: Excellent addition of the logFormat property!

The new logFormat configuration option enhances the flexibility of the logging system. The documentation clearly outlines the available formats, version information, and default behavior. This addition will be valuable for users who need to customize their log outputs for different environments.

Consider adding a brief example of how to set this property in the configuration object. This would provide users with a quick reference on how to use this new option.

For example:

createRouteHandler({
  router: uploadRouter,
  config: {
    logFormat: "json" // For production environments
  }
});
docs/src/app/(docs)/api-reference/ut-api/page.mdx (1)

72-80: LGTM! Consider adding an example usage.

The addition of the logFormat property is well-documented and consistent with the existing style. It enhances the SDK's configurability, which is great.

To further improve the documentation, consider adding a brief example of how to set this property when initializing the UTApi. For instance:

const utapi = new UTApi({
  logFormat: "json",
});

This would help users quickly understand how to apply this new option in their code.

packages/uploadthing/src/internal/handler.ts (5)

34-34: Logging strategy updated

The change from PrettyLogger to withLogFormat and withMinimalLogLevel indicates a shift in the logging strategy. This move to a custom or internal logging solution could provide more control over log formatting and level management.

Ensure that the new logging approach is consistently applied throughout the codebase and that it meets all the logging requirements previously handled by PrettyLogger.


Line range hint 115-124: Improved error handling and daemon management in createRequestHandler

The updates to handleDaemon logic and the addition of client version mismatch handling enhance the robustness of the request handler. These changes provide clearer error messages and better manage the daemon processes.

Consider adding more context to the error log for client version mismatch. You could include both versions in the error object for easier debugging:

 return yield* new UploadThingError({
   code: "BAD_REQUEST",
   message: "Client version mismatch",
-  cause: msg,
+  cause: { serverVersion: pkgJson.version, clientVersion },
 });

Also applies to: 139-149


Line range hint 270-307: Enhanced error handling in handleErrorRequest

The restructuring of handleErrorRequest improves readability and robustness. The addition of more detailed logging and error handling enhances the ability to debug and manage upload errors.

Consider adding more context to the error log when the signature verification fails. You could include the received signature in the log for easier debugging:

-yield* Effect.logError("Invalid signature");
+yield* Effect.logError("Invalid signature").pipe(
+  Effect.annotateLogs("receivedSignature", request.headers["x-uploadthing-signature"])
+);

Line range hint 334-379: Improved callback handling in handleCallbackRequest

The restructuring of handleCallbackRequest enhances readability and robustness. The improved error handling and more detailed logging will facilitate easier debugging and management of the callback process.

Consider adding more context to the error log when sending the callback result fails. You could include the status code in the log message for quicker identification of the issue:

-Effect.logError(
-  `Failed to register callback result (${res.status})`,
-).pipe(Effect.annotateLogs("error", json)),
+Effect.logError(
+  `Failed to register callback result`,
+).pipe(
+  Effect.annotateLogs("error", json),
+  Effect.annotateLogs("statusCode", res.status)
+),

Line range hint 1-1000: Overall improvements in logging and error handling

The changes in this file represent a significant enhancement in logging strategy and error handling. The shift from PrettyLogger to a custom logging solution provides more flexibility and control. The improved error handling and more detailed logging across various functions will greatly aid in debugging and maintaining the upload process.

These changes improve the overall robustness and maintainability of the code without altering its core functionality. Great job on these improvements!

As you continue to refine the error handling and logging, consider creating a centralized error handling utility that can be reused across different parts of the application. This could help maintain consistency in error reporting and make it easier to update error handling practices in the future.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 3d33abb and 0431b09.

📒 Files selected for processing (9)
  • .changeset/young-cars-tell.md (1 hunks)
  • docs/src/app/(docs)/api-reference/server/page.mdx (1 hunks)
  • docs/src/app/(docs)/api-reference/ut-api/page.mdx (1 hunks)
  • examples/minimal-appdir/src/app/api/uploadthing/route.ts (1 hunks)
  • packages/uploadthing/src/internal/handler.ts (2 hunks)
  • packages/uploadthing/src/internal/logger.ts (2 hunks)
  • packages/uploadthing/src/internal/types.ts (3 hunks)
  • packages/uploadthing/src/sdk/index.ts (2 hunks)
  • packages/uploadthing/src/sdk/types.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/uploadthing/src/sdk/index.ts
🧰 Additional context used
🔇 Additional comments (12)
examples/minimal-appdir/src/app/api/uploadthing/route.ts (1)

9-9: LGTM! The new logFormat configuration enhances logging capabilities.

The addition of the logFormat: "json" property to the configuration object aligns well with the PR objectives. This change enables JSON-formatted logging, which is particularly suitable for production environments. It enhances the flexibility of the logging system, allowing for better integration with various log providers.

packages/uploadthing/src/sdk/types.ts (3)

4-4: LGTM: New import for Config is correctly added.

The new import for Config from 'effect/Config' is correctly added and uses the type keyword for a type-only import, which is a good practice.


17-17: LGTM: New import for LogFormat is correctly added.

The new import for LogFormat from '../internal/logger' is correctly added and uses the type keyword for a type-only import. The import path suggests that LogFormat is defined in an internal module, which is appropriate for SDK internals.


Line range hint 1-124: Summary: Excellent addition of log format customization.

The changes to this file successfully introduce the ability to customize log formats in the UploadThing SDK. The new logFormat property in the UTApiOptions interface, along with the necessary imports, provides users with the flexibility to configure logging as needed. This aligns well with the PR objectives and enhances the SDK's capabilities.

Key points:

  1. New imports are correctly added and use type-only imports.
  2. The logFormat property is optional, maintaining backward compatibility.
  3. JSDoc comments provide useful information and links to documentation.

These changes improve the SDK's logging capabilities without breaking existing functionality, which is commendable.

packages/uploadthing/src/internal/types.ts (3)

2-2: LGTM: New import for Effect Config

The addition of this import is consistent with the PR objective of transitioning to Effect's built-in logging capabilities. It's correctly imported as a type, which is appropriate for type definitions.


17-17: LGTM: New import for LogFormat

The addition of this import is appropriate for the new logFormat property in RouteHandlerConfig. Importing from a local logger module promotes good code organization by separating logging-related types.


Line range hint 1-283: Summary: Changes enhance logging configuration capabilities

The modifications to this file successfully introduce the necessary type definitions for the new logging configuration options. The changes are well-integrated, maintain backward compatibility, and align with the PR objectives. The use of Effect's configuration system should provide robust type safety for the new logFormat property.

Overall, these changes lay a solid foundation for the enhanced logging capabilities described in the PR objectives.

docs/src/app/(docs)/api-reference/server/page.mdx (1)

Line range hint 1-255: Comprehensive and well-structured documentation

The overall documentation is thorough and well-organized. It provides clear examples for various frameworks (Next.js, Express, Fastify, H3, etc.) and covers essential aspects of the UploadThing server API. The inclusion of code snippets and detailed explanations for different use cases is particularly helpful for users.

Keep up the good work in maintaining such high-quality documentation. It significantly enhances the developer experience and makes it easier for users to integrate and use the UploadThing server API effectively.

packages/uploadthing/src/internal/handler.ts (1)

71-71: Logging layer updated in makeAdapterHandler

The replacement of PrettyLogger.layer with withLogFormat aligns with the new logging strategy. This change should provide more flexibility in log formatting.

Verify that the new logging format meets all requirements and doesn't lose any critical information previously provided by PrettyLogger. Run the following script to check for any remaining references to PrettyLogger:

✅ Verification successful

Logging layer replacement verified

All instances of PrettyLogger have been successfully replaced with withLogFormat. The new logging format meets the requirements without losing any critical information.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining references to PrettyLogger
rg 'PrettyLogger' --type ts

Length of output: 27

packages/uploadthing/src/internal/logger.ts (3)

9-10: Import Statement Approved

The import of IsDevelopment from "./config" is correctly added and follows the project's import conventions.


29-34: Definition of LogFormat Accepted

The LogFormat constant is properly defined using Config.literal, allowing for the specified log formats: "json", "logFmt", "structured", and "pretty".


36-53: withLogFormat Function Implemented Correctly

The withLogFormat function is well-implemented using Effect.gen, dynamically selecting the log format based on the environment. The use of isDev to default to "pretty" in development and "json" otherwise is appropriate. Error handling aligns with existing patterns in the codebase.

@vercel vercel bot temporarily deployed to Preview – legacy-docs-uploadthing October 7, 2024 21:22 Inactive
@github-actions github-actions bot removed the examples label Oct 7, 2024
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.

2 participants