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: The trace of log can be clicked as a link #735

Merged
merged 5 commits into from
Nov 29, 2024
Merged

Conversation

kkumar-gcc
Copy link
Member

@kkumar-gcc kkumar-gcc commented Nov 26, 2024

📑 Description

Closes goravel/goravel#397

photo_2024-11-26_20-51-58

Summary by CodeRabbit

  • New Features

    • Improved formatting for stack traces, enhancing readability by presenting file paths first, followed by method names in brackets.
  • Bug Fixes

    • Adjusted test cases to align with the new stack trace formatting, ensuring accurate validation of the formatStackTraces method.

✅ Checks

  • Added test cases for my code

@kkumar-gcc kkumar-gcc requested a review from a team as a code owner November 26, 2024 15:39
Copy link
Contributor

coderabbitai bot commented Nov 26, 2024

Walkthrough

The changes involve modifications to the formatStackTraces method in the log/formatter/general.go file, enhancing the formatting of stack trace entries. A new function, formatStackTrace, has been introduced to extract and format file line numbers and method names from stack trace strings. Corresponding updates were made in the log/formatter/general_test.go file to adjust the test cases for the new stack trace format while maintaining the overall structure of the tests.

Changes

File Change Summary
log/formatter/general.go Added formatStackTrace function to improve stack trace formatting in formatStackTraces.
log/formatter/general_test.go Updated TestFormatStackTraces to reflect new stack trace format; assertions adjusted. Added TestFormatStackTrace for individual stack trace scenarios.

Assessment against linked issues

Objective Addressed Explanation
Enhance stack trace readability (#[397]) The changes do not implement clickable links for stack traces as described in the feature request.

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.

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

🧹 Outside diff range and nitpick comments (1)
log/formatter/general_test.go (1)

221-224: Consider adding more test cases for robustness

While the current test cases verify the basic functionality, consider adding:

  1. Test cases for malformed stack traces (missing line numbers, colons, or brackets)
  2. Test cases that explicitly verify the clickable nature of the links (format matches IDE expectations)

Here's a suggested test case to add:

 tests := []struct {
   name   string
   setup  func()
   assert func()
 }{
+  {
+    name: "Malformed stack trace",
+    setup: func() {
+      stackTraces = map[string]any{
+        "root": map[string]any{
+          "message": "error",
+          "stack": []string{
+            "malformed/path/no/line/number [method]",
+            "malformed/path/no/brackets:123",
+            "just/a/path",
+          },
+        },
+      }
+    },
+    assert: func() {
+      traces, err := general.formatStackTraces(stackTraces)
+      s.NotNil(err)
+      s.Contains(err.Error(), "invalid stack trace format")
+    },
+  },
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c793486 and 0f93dae.

📒 Files selected for processing (2)
  • log/formatter/general.go (1 hunks)
  • log/formatter/general_test.go (2 hunks)
🔇 Additional comments (3)
log/formatter/general.go (1)

125-134: Verify the stack trace format across different environments

The current parsing logic makes assumptions about the stack trace format. We should verify that this works consistently across different environments and error types.

✅ Verification successful

Let me gather more information about the stack trace formatting implementation and its tests.


Let me check the actual implementation of the formatStackTraces function.


Stack trace parsing implementation is well-tested and handles format variations

The implementation is safe and well-structured for the following reasons:

  • The code has comprehensive test coverage with test cases for both nil and structured stack traces
  • The StackTrace struct properly defines the expected format
  • The parsing logic has fallback handling: if the expected format (with two colons) isn't found, it prints the raw stack trace line
  • The test suite includes a realistic example that matches the production format: /dummy/examples/logging/example.go:143 [main.main]
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for stack trace generation patterns in the codebase
rg -A 5 'runtime\.Stack|debug\.Stack|stacktrace|stack trace' 

# Look for existing stack trace format tests
rg -A 10 'TestFormatStackTraces|test.*stack.*trace' --type go

Length of output: 3670


Script:

#!/bin/bash
# Check the stack trace formatting test implementation
cat log/formatter/general_test.go

# Look for actual stack trace format implementation
ast-grep --pattern 'func $_ formatStackTraces($_) {
  $$$
}'

Length of output: 6703


Script:

#!/bin/bash
# Look for the formatStackTraces implementation in the general.go file
cat log/formatter/general.go

Length of output: 3576

log/formatter/general_test.go (2)

211-212: LGTM! Wrap trace format is consistent

The wrap trace maintains the same clickable format as the main stack traces, ensuring consistency throughout the error chain.


203-206: LGTM! Stack trace format is IDE-friendly

The new stack trace format filepath:line [method] is well-structured and follows the common IDE-clickable format. This change aligns with the PR objective of making log traces clickable as links.

Let's verify the format consistency across the codebase:

✅ Verification successful

Let me verify the stack trace format consistency with a more targeted search:


Let me try a different search pattern to verify the stack trace format:


Let me check the entire test file context around these stack traces:


Stack trace format is consistent and well-structured

The stack trace format consistently follows the pattern filepath:line [method] throughout the test file, both in the input data and expected output assertions. All stack traces maintain this IDE-friendly format that makes them clickable:

  • Input format: /dummy/examples/logging/example.go:143 [main.main]
  • Expected format: /dummy/examples/logging/example.go:143 [main.main]
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any inconsistent stack trace formats in test files
rg -g '**/*_test.go' '(?<!:)\d+\s+\[' # Find traces without the filepath:line format
rg -g '**/*_test.go' '\][^\]]' # Find traces where method is not properly bracketed

Length of output: 145864


Script:

#!/bin/bash
# Search for stack trace patterns in test files
rg --pcre2 'filepath:\d+\s+\[[\w\.]+\]' log/formatter/

Length of output: 56


Script:

#!/bin/bash
# Search for stack trace patterns in test files
rg "\"stack\".*\[" log/formatter/

Length of output: 229


Script:

#!/bin/bash
# Get the full test context
rg -A 10 '"stack".*\[' log/formatter/general_test.go

Length of output: 991

log/formatter/general.go Outdated Show resolved Hide resolved
Copy link

codecov bot commented Nov 26, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 69.40%. Comparing base (d873424) to head (831df3e).
Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master     #735      +/-   ##
==========================================
+ Coverage   69.38%   69.40%   +0.01%     
==========================================
  Files         210      210              
  Lines       17030    17040      +10     
==========================================
+ Hits        11817    11827      +10     
  Misses       4556     4556              
  Partials      657      657              

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

coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 26, 2024
Copy link
Contributor

@hwbrzzl hwbrzzl left a comment

Choose a reason for hiding this comment

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

Great implement! Just one tip.

log/formatter/general.go Outdated Show resolved Hide resolved
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 (1)
log/formatter/general.go (1)

132-143: Add test cases for the new formatStackTrace function

To ensure reliability and catch edge cases, we should add unit tests for the new function. Test cases should cover:

  1. Valid stack traces with file:line and method
  2. Invalid formats
  3. Edge cases (empty string, missing parts)

Would you like me to help generate comprehensive test cases for this function? This would help fulfill the PR objective's testing requirement.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0f93dae and f645fd3.

📒 Files selected for processing (1)
  • log/formatter/general.go (1 hunks)
🔇 Additional comments (2)
log/formatter/general.go (2)

125-125: LGTM! Good separation of concerns.

The extraction of formatting logic into a separate function improves testability and code organization.


132-143: ⚠️ Potential issue

Implementation needs revision to make traces clickable

The current implementation has several issues:

  1. The format doesn't follow IDE/terminal patterns for clickable files
  2. String manipulation is fragile without proper validation
  3. The implementation doesn't achieve the PR objective of making traces clickable

Consider this revised implementation that follows standard IDE patterns:

 func formatStackTrace(stackStr string) string {
-    lastColon := strings.LastIndex(stackStr, ":")
-    if lastColon > 0 && lastColon < len(stackStr)-1 {
-        secondLastColon := strings.LastIndex(stackStr[:lastColon], ":")
-        if secondLastColon > 0 {
-            fileLine := stackStr[secondLastColon+1:]
-            method := stackStr[:secondLastColon]
-            return fmt.Sprintf("\t%s [%s]\n", fileLine, method)
-        }
-    }
-    return fmt.Sprintf("\t%s\n", stackStr)
+    // Split into file:line and method
+    parts := strings.Split(stackStr, " ")
+    if len(parts) < 2 {
+        return fmt.Sprintf("\t%s\n", stackStr)
+    }
+    
+    // Validate file location format (path:line)
+    fileLocation := parts[0]
+    if !strings.Contains(fileLocation, ":") {
+        return fmt.Sprintf("\t%s\n", stackStr)
+    }
+    
+    // Format as "file:line method" to enable IDE/terminal click-to-file
+    method := strings.Join(parts[1:], " ")
+    return fmt.Sprintf("\t%s %s\n", fileLocation, method)
}

This revision:

  1. Preserves the file:line format that IDEs/terminals recognize as clickable
  2. Adds proper validation of the input format
  3. Maintains a cleaner separation between file location and method name

Let's verify if the stack trace format matches common IDE patterns:

#!/bin/bash
# Check if the stack trace format matches common IDE patterns
# Example: should match patterns like "/path/to/file.go:123"

# Search for current stack trace formats in the codebase
rg -A 2 'file\.go:\d+'

# Search for any existing clickable file patterns
ast-grep --pattern 'fmt.Sprintf("\t%s %s\n", $file, $_)'

coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 28, 2024
Copy link
Member

@devhaozi devhaozi left a comment

Choose a reason for hiding this comment

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

LGTM

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 (1)
log/formatter/general_test.go (1)

241-300: LGTM! Comprehensive test coverage with room for enhancement.

The test cases thoroughly cover various scenarios using a well-structured table-driven approach. Consider adding these additional test cases to improve coverage:

 tests := []struct {
     name     string
     input    string
     expected string
 }{
     // ... existing test cases ...
+    {
+        name:     "Malformed path with spaces",
+        input:    "main.handler:/path with spaces/file.go:42",
+        expected: "\t/path with spaces/file.go:42 [main.handler]\n",
+    },
+    {
+        name:     "Path with special characters",
+        input:    "handler:/path/with-#special@chars/file.go:42",
+        expected: "\t/path/with-#special@chars/file.go:42 [handler]\n",
+    },
+    {
+        name:     "Windows-style path",
+        input:    "main.handler:C:\\path\\to\\file.go:42",
+        expected: "\tC:\\path\\to\\file.go:42 [main.handler]\n",
+    },
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f645fd3 and 0ff312d.

📒 Files selected for processing (1)
  • log/formatter/general_test.go (3 hunks)
🔇 Additional comments (2)
log/formatter/general_test.go (2)

203-206: LGTM! Test data updated to reflect new clickable format.

The stack trace format changes consistently follow the new pattern of filepath:line [method], which aligns with making traces clickable as links.

Also applies to: 211-212, 221-224


241-300: Verify format compatibility with common development tools.

While the new format positions file paths for clickability, we should verify that it works as expected with common IDEs and tools. Could you:

  1. List the development tools/IDEs this format has been tested with
  2. Add a comment in the test file documenting the supported tools

@kkumar-gcc kkumar-gcc enabled auto-merge (squash) November 29, 2024 18:14
@kkumar-gcc kkumar-gcc merged commit 65c6a08 into master Nov 29, 2024
12 checks passed
@kkumar-gcc kkumar-gcc deleted the kkumar-gcc/#397 branch November 29, 2024 18:23
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.

✨ [Feature] The trace of log can be clicked as a link
3 participants