Skip to content

feat: add log rotation for forester - #1875

Merged
sergeytimoshin merged 1 commit into
mainfrom
sergey/forester-rolling-logs
Jul 21, 2025
Merged

feat: add log rotation for forester#1875
sergeytimoshin merged 1 commit into
mainfrom
sergey/forester-rolling-logs

Conversation

@sergeytimoshin

@sergeytimoshin sergeytimoshin commented Jul 21, 2025

Copy link
Copy Markdown
Contributor

Added log rotation with 48-hour retention (2 days) and fallback to stdout logging when file appender creation fails.

Summary by CodeRabbit

  • Bug Fixes

    • Improved reliability of log file creation and error handling; if log files cannot be created, logging will continue to standard output without interruption.
  • Refactor

    • Simplified log level settings to default to "info" for both general and stdout logging.
    • Enhanced internal handling of log file rotation and retention for better stability.

Added log rotation with 48-hour retention (2 days) and fallback to
stdout logging when file appender creation fails.
@coderabbitai

coderabbitai Bot commented Jul 21, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The telemetry setup logic was refactored to use a builder pattern for configuring the rolling file appender, with improved error handling. If file logging cannot be initialized, the system now logs a warning and defaults to stdout-only logging. Logging filters were simplified to default to "info" level, and control flow was updated accordingly.

Changes

File(s) Change Summary
forester/src/telemetry.rs Refactored telemetry setup to use a builder for file appender, improved error handling, simplified log filters, and conditionally enabled file logging based on appender creation success.

Sequence Diagram(s)

sequenceDiagram
    participant App
    participant Telemetry
    participant FileAppender
    participant Stdout

    App->>Telemetry: setup_telemetry()
    Telemetry->>FileAppender: try create rolling file appender (builder)
    alt Success
        FileAppender-->>Telemetry: appender created
        Telemetry->>Telemetry: setup file logging layer
        Telemetry->>Stdout: setup stdout logging layer
        Telemetry->>App: initialize subscriber with file and stdout layers
    else Failure
        FileAppender-->>Telemetry: error
        Telemetry->>Telemetry: print warning to stderr
        Telemetry->>Stdout: setup stdout logging layer only
        Telemetry->>App: initialize subscriber with stdout layer only
    end
Loading

Estimated code review effort

2 (~15 minutes)

Poem

Logs now roll with builder’s might,
And errors handled, not out of sight.
If files can’t write, a warning will show,
To stdout-only the logs will go.
The filters are simple, the flow is clean—
A rabbit’s delight, serene and keen! 🐇

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 8355614 and 2c4097b.

📒 Files selected for processing (1)
  • forester/src/telemetry.rs (1 hunks)
🔇 Additional comments (4)
forester/src/telemetry.rs (4)

11-26: LGTM: Well-implemented builder pattern with proper error handling.

The builder pattern implementation for the rolling file appender is excellent. The configuration is clear and the error handling gracefully falls back to stdout-only logging when file operations fail.

The log retention of 48 files (2 days with hourly rotation) aligns perfectly with the PR objectives.


28-32: Good simplification of environment filters.

The change from potentially complex filters to defaulting to "info" level is a sensible simplification that improves maintainability.


39-58: Well-structured conditional logging setup.

The conditional initialization based on file appender success is well-implemented, ensuring logging continues regardless of file system issues.


15-15: Please verify disk usage for hourly log rotation

The code retains 48 hourly log files (2 days), which meets the PR objectives. Before approving, confirm this retention level is acceptable in your deployment:

  • Measure current log sizes, for example:
    du -sh logs/forester*.log | awk '{sum += $1} END {print "Total:", sum}'
    du -sh logs | grep forester
  • Calculate: average log size × 48
  • Ensure the total fits within your available disk budget

[file: forester/src/telemetry.rs Lines 15]
.max_log_files(48) // 2 days

Comment thread forester/src/telemetry.rs

// Keep _guard in scope to keep the non-blocking writer alive
std::mem::forget(_guard);
std::mem::forget(_guard);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Memory leak: Replace std::mem::forget with proper guard management.

Using std::mem::forget(_guard) intentionally leaks memory, which is problematic for long-running applications. The guard should be stored and managed properly.

Consider one of these solutions:

Solution 1 (Recommended): Store the guard in a static

+use std::sync::Mutex;
+use once_cell::sync::Lazy;
+
+static GUARD: Lazy<Mutex<Option<tracing_appender::non_blocking::WorkerGuard>>> = 
+    Lazy::new(|| Mutex::new(None));

 // Inside the function:
-std::mem::forget(_guard);
+*GUARD.lock().unwrap() = Some(_guard);

Solution 2: Use a leaked Box for controlled memory management

-std::mem::forget(_guard);
+Box::leak(Box::new(_guard));

Solution 3: Accept the guard will be dropped and document the trade-off

-std::mem::forget(_guard);
+// Note: Guard is intentionally dropped here, which may cause log loss
+// during shutdown, but prevents memory leaks in long-running processes
🤖 Prompt for AI Agents
In forester/src/telemetry.rs at line 52, the use of std::mem::forget(_guard)
causes a memory leak by intentionally preventing the guard from being dropped.
To fix this, replace std::mem::forget with proper guard management by storing
the guard in a static variable to keep it alive for the program's duration, or
alternatively use a leaked Box to manage the memory more explicitly. Avoid
forgetting the guard without tracking it, ensuring it is properly stored and
managed to prevent leaks.

@sergeytimoshin
sergeytimoshin merged commit 791d46f into main Jul 21, 2025
@sergeytimoshin
sergeytimoshin deleted the sergey/forester-rolling-logs branch July 21, 2025 17:52
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