Skip to content

Conversation

@brunodmartins
Copy link
Contributor

@brunodmartins brunodmartins commented May 9, 2025

Description

Fixes #3436.

Changing the log format tags to read the requestid from the context, since the key values from Locals API was changed due to the keys collisions. See more on #2684

Type of change

  • Fix (non-breaking change which adds fix a functionality)

Checklist

Before you submit your pull request, please make sure you meet these requirements:

  • Followed the inspiration of the Express.js framework for new functionalities, making them similar in usage.
  • Conducted a self-review of the code and provided comments for complex or critical parts.
  • Updated the documentation in the /docs/ directory for Fiber's documentation.
  • Added or updated unit tests to validate the effectiveness of the changes or new features.
  • Ensured that new and existing unit tests pass locally with the changes.
  • Verified that any new dependencies are essential and have been agreed upon by the maintainers/community.
  • Aimed for optimal performance with minimal allocations in the new code.
  • Provided benchmarks for the new code to analyze and improve upon.

Commit formatting

Please use emojis in commit messages for an easy way to identify the purpose or intention of a commit. Check out the emoji cheatsheet here: CONTRIBUTING.md

@brunodmartins brunodmartins requested a review from a team as a code owner May 9, 2025 02:19
@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 9, 2025

Walkthrough

The change updates the logger middleware to support the extraction of the request ID when using the locals:requestid tag in log formats. The implementation checks for the "requestid" parameter and retrieves the value from the context using the requestid middleware, ensuring the request ID is logged as expected.

Changes

File(s) Change Summary
middleware/logger/tags.go Added import for requestid middleware and updated createTagMap to support locals:requestid

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant FiberApp
    participant LoggerMiddleware
    participant RequestIDMiddleware

    Client->>FiberApp: Sends HTTP request
    FiberApp->>RequestIDMiddleware: Process request
    RequestIDMiddleware->>FiberApp: Attach request ID to context
    FiberApp->>LoggerMiddleware: Pass context
    LoggerMiddleware->>LoggerMiddleware: Check for locals:requestid tag
    LoggerMiddleware->>RequestIDMiddleware: Retrieve request ID from context
    LoggerMiddleware->>FiberApp: Log request with request ID
    FiberApp->>Client: Send response
Loading

Assessment against linked issues

Objective Addressed Explanation
Fix logger so that locals:requestid correctly logs the request ID (Issue #3436)

Possibly related PRs

Suggested labels

☢️ Bug, v3

Suggested reviewers

  • sixcolors
  • efectn
  • ReneWerner87

Poem

A rabbit with logs, so clever and spry,
Now captures request IDs as they hop by.
With each little nibble of context and tag,
The logger now boasts a new trick in its bag.
🐇✨ No more empty fields—just IDs that fly!

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8d18b42 and 9b41a6d.

📒 Files selected for processing (1)
  • middleware/logger/tags.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • middleware/logger/tags.go
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Compare
  • GitHub Check: repeated
  • GitHub Check: unit (1.24.x, windows-latest)
  • GitHub Check: unit (1.23.x, windows-latest)
✨ Finishing Touches
  • 📝 Generate Docstrings

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

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

@codecov
Copy link

codecov bot commented May 9, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 83.94%. Comparing base (bfef962) to head (9b41a6d).
Report is 3 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3441      +/-   ##
==========================================
+ Coverage   83.85%   83.94%   +0.09%     
==========================================
  Files         119      119              
  Lines       11897    11900       +3     
==========================================
+ Hits         9976     9990      +14     
+ Misses       1490     1482       -8     
+ Partials      431      428       -3     
Flag Coverage Δ
unittests 83.94% <100.00%> (+0.09%) ⬆️

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.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@brunodmartins brunodmartins force-pushed the gh-3436 branch 2 times, most recently from 499ddcc to 8d18b42 Compare May 9, 2025 02:40
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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 1

🛑 Comments failed to post (1)
middleware/logger/tags.go (1)

5-5: ⚠️ Potential issue

Fix the import formatting to resolve the golangci-lint error.

The import statement for the requestid middleware is not properly formatted according to gofumpt, as indicated by the static analysis and pipeline failures. Go imports should be organized into groups (standard library first, then third-party packages).

Fix the import formatting by running:

go fmt ./...
# or preferably
gofumpt -l -w .
🧰 Tools
🪛 GitHub Check: lint

[failure] 5-5:
File is not properly formatted (gofumpt)

🪛 GitHub Actions: golangci-lint

[error] 5-5: File is not properly formatted (gofumpt)

@brunodmartins
Copy link
Contributor Author

I made a first version of the PR changing the contextKey to be a string, which would fix the problem on the log! But when I saw the linked issue related to the collision of contextKeys, I made this new version. The one downside I see with my approach is that we are now making a dependency from the logger package to middleware/requestid, which seems wrong to be.

I would prefer to the first version which could cause collision. But I am opened to suggestions and reviews :)

@ReneWerner87
Copy link
Member

ReneWerner87 commented May 12, 2025

@sixcolors we use the pattern with the inaccessible context keys with some middlewares
#2781

since we only have string possibilities in the logger pattern, the question is how we solve this cleanly
the logger middleware should also be independent of the other middlewares
I would be interested in ideas @gofiber/maintainers @gofiber/contributors

@nickajacks1
Copy link
Member

nickajacks1 commented May 12, 2025

Hm, did locals:requestid work in the past? It's no longer stored in locals, so it not working is technically "correct". I wouldn't mind this solution, but maybe adding a separate tag makes sense. I dont think the added dependency is a big deal because it's all under the main fiber module anyway.

CustomTags is always an option too :)

Copy link
Member

@sixcolors sixcolors left a comment

Choose a reason for hiding this comment

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

Closes #3436

This is expected behavior and doesn’t require any changes to the logger.

As noted in the referenced issue #2684, the reason Locals("requestid") no longer works in v3 is because Fiber middlewares—like requestid—follow Go’s context best practices, which state:

“The provided key must be comparable and should not be of type string or any other built-in type to avoid collisions between packages using context. Users of WithValue should define their own types for keys.”

To comply, middleware values are stored in the context using unexported keys of custom types rather than strings. As a result, values like the request ID aren’t accessible directly via Locals with a string key.


Recommended: use CustomTags

For most users, the cleanest and most maintainable way to include middleware values in your logs is via the CustomTags option:

app.Use(logger.New(logger.Config{
    CustomTags: map[string]logger.LogFunc{
        "requestid": func(out logger.Buffer, c fiber.Ctx, _ *logger.Data, _ string) (int, error) {
            return out.WriteString(requestid.FromContext(c))
        },
    },
    Format: "[${time}] ${ip} ${method} ${path} ${status} - requestid=${requestid}\n",
}))
  • Keeps logger decoupled from other middleware
  • No need to touch Locals at all
  • Fully configurable naming, formatting, and behaviour

General case: use Locals

If you prefer or already have a pattern that accesses values from Locals, you can manually copy the context value into Locals:

app.Use(func(c fiber.Ctx) error {
    c.Locals("requestid", requestid.FromContext(c))
    return c.Next()
})
  • Works with existing Locals-based logging
  • Gives you control over when and how values get set

Both approaches follow Go’s best practices and keep your logger free of unsafe assumptions or hidden dependencies. Feel free to choose whichever fits your project style!

@gaby
Copy link
Member

gaby commented May 13, 2025

Let's close this in favor of #3446

@gaby
Copy link
Member

gaby commented May 13, 2025

@brunodmartins Thanks! We are closing this in favor of #3446 which improves the documentation with the correct way of showing a RequestID.

@gaby gaby closed this May 13, 2025
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.

🐛 [Bug]: logger locals:requestid not working

5 participants