Skip to content

🔥 feat: Add support for ForceColors in Logger middleware #3428

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

Open
wants to merge 7 commits into
base: main
Choose a base branch
from

Conversation

yorickdewid
Copy link

@yorickdewid yorickdewid commented Apr 28, 2025

Description

  • Force the use of colors in the terminal if the user enables this explicitly.
  • Included a single unit test Test_Logger_ForceColors to test this behavior.

Fixes #3400

@yorickdewid yorickdewid requested a review from a team as a code owner April 28, 2025 10:13
Copy link

welcome bot commented Apr 28, 2025

Thanks for opening this pull request! 🎉 Please check out our contributing guidelines. If you need help or want to chat with us, join us on Discord https://gofiber.io/discord

Copy link
Contributor

coderabbitai bot commented Apr 28, 2025

Walkthrough

A new boolean field, ForceColors, has been introduced to the logger middleware configuration, allowing colorized output to be forcibly enabled regardless of terminal detection or environment variables. The logic for enabling colors in both the configuration and runtime logger output has been updated to respect this new flag. Additionally, a dedicated test verifies that color output is produced even when colors are otherwise disabled, provided ForceColors is set to true.

Changes

File(s) Change Summary
middleware/logger/config.go Added ForceColors to Config struct; updated color enabling logic to consider ForceColors.
middleware/logger/default_logger.go Modified logger output logic to honor ForceColors, overriding environment/terminal checks as needed.
middleware/logger/logger_test.go Added test Test_Logger_ForceColors to verify forced color output in logger middleware; added benchmarks with ForceColors.
docs/middleware/logger.md Updated documentation to include ForceColors option with description, default, and usage example.
docs/whats_new.md Added ForceColors field description and usage note to Fiber v3 logging middleware documentation.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant FiberApp
    participant LoggerMiddleware
    participant Config

    User->>FiberApp: Sends HTTP request
    FiberApp->>LoggerMiddleware: Handles request
    LoggerMiddleware->>Config: Checks ForceColors, DisableColors, terminal/env
    alt ForceColors is true
        LoggerMiddleware->>LoggerMiddleware: Enable colors in output
    else ForceColors is false
        LoggerMiddleware->>LoggerMiddleware: Use standard color detection logic
    end
    LoggerMiddleware->>FiberApp: Continues processing
    FiberApp->>User: Returns response
Loading

Assessment against linked issues

Objective Addressed Explanation
Introduce a new config option forceColors to enable colors regardless of terminal check (#3400)
Modify logger logic to respect forceColors and override terminal and environment checks (#3400)
Provide test coverage verifying forced color output when forceColors is true (#3400)
Update documentation to include forceColors configuration option (#3400)

Suggested reviewers

  • ReneWerner87
  • gaby
  • sixcolors

Poem

A bunny with a rainbow brush,
Now paints the logs in colors lush.
No terminal check can dim its art—
With ForceColors, hues won't depart!
Through tests and code, the colors flow,
In Fiber's logs, a vivid show.
🐇🌈

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 fd76f97 and 5a705f2.

📒 Files selected for processing (1)
  • docs/whats_new.md (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • docs/whats_new.md

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

@gaby
Copy link
Member

gaby commented Apr 28, 2025

@yorickdewid Please update the documentation in the docs directory.

Also add an entry in docs/whats_new.md.

@gaby gaby added this to v3 Apr 28, 2025
@gaby gaby added this to the v3 milestone Apr 28, 2025
@gaby gaby moved this to In Progress in v3 Apr 28, 2025
@gaby gaby changed the title Force the use of terminal colors via config option 🔥 feat: Add support for ForceColors in Logger middleware Apr 28, 2025
Copy link

codecov bot commented Apr 28, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 83.97%. Comparing base (85cce3c) to head (c430a84).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3428      +/-   ##
==========================================
+ Coverage   83.87%   83.97%   +0.10%     
==========================================
  Files         119      119              
  Lines       11892    11892              
==========================================
+ Hits         9974     9986      +12     
+ Misses       1488     1479       -9     
+ Partials      430      427       -3     
Flag Coverage Δ
unittests 83.97% <100.00%> (+0.10%) ⬆️

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.

@gaby gaby requested a review from Copilot April 28, 2025 12:13
Copy link
Contributor

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR adds support for forcing colors in the Logger middleware even when the terminal might not normally support them. Key changes include the introduction of a new unit test for ForceColors, modifications in the logger's color handling logic in the default logger file, and updates to the configuration defaults to enable color forcing.

Reviewed Changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated no comments.

File Description
middleware/logger/logger_test.go Added a unit test to validate ForceColors behavior
middleware/logger/default_logger.go Adjusted the color handling logic to account for the ForceColors flag
middleware/logger/config.go Updated configuration to include the ForceColors option and update enableColors logic
Comments suppressed due to low confidence (1)

middleware/logger/default_logger.go:150

  • Overwriting the provided Stream unconditionally may cause unexpected behavior, particularly when a custom writer (such as a buffer for testing) is supplied. Consider checking if a custom Stream is already provided before overriding it.
cfg.Stream = colorable.NewColorableStdout()

@yorickdewid
Copy link
Author

@gaby Where do you want me to add this 'ForceColors' in the whats new. The App section or the Logging section?

Also, Am I seeing this correctly that the use of colors in the output is never actually tested? From what I gather the only testcase doing something with color is Test_Logger_All (logger_test.go). This doesn't test the use of colors, just that the colors in the output match the ColorScheme. For example colors are used in the ${status} tag, but this tag is not tested in the output. Can you confirm this?

@yorickdewid
Copy link
Author

@gaby

@ReneWerner87
Copy link
Member

@yorickdewid thanks for this feature, can you check the review hints and add it to our "what´s new" overview

@ReneWerner87
Copy link
Member

@yorickdewid Logger section sounds good

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0d32fe6 and fd76f97.

📒 Files selected for processing (1)
  • docs/whats_new.md (1 hunks)

@ReneWerner87
Copy link
Member

@yorickdewid thanks for the customization
in the tests i would say before it was not really possible to test the colors because you could not force it
now it should be possible because you can activate the switch and not look and decide for yourself if the console supports colors
i.e. the best would be a test where you force colors by collecting the content with a buffer writer and check if the color codes are in the right places in the format
This of course ensures that we can make sure that the feature works after customization in the future and that we find errors in other pull requests faster

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Status: In Progress
Development

Successfully merging this pull request may close these issues.

📝 [Proposal]: Force color logging
4 participants