feat: [#3] Setup logging for production CLI with configurable options#4
Merged
josecelano merged 6 commits into3-setup-logging-for-production-clifrom Oct 16, 2025
Conversation
Copilot
AI
changed the title
[WIP] Setup logging for production CLI application
feat: [#3] Setup logging for production CLI with configurable options
Oct 15, 2025
josecelano
requested changes
Oct 15, 2025
Member
There was a problem hiding this comment.
@copilot, It looks good. I have added only two things to fix.
Add comprehensive specification for removing ANSI color codes from log files when using compact and pretty formats. Recommends independent format control (--log-file-format, --log-stderr-format) to give users full control over logging behavior. Discovered during PR #4 review. JSON format already works correctly. Related to #2, #3
Member
31 tasks
josecelano
approved these changes
Oct 15, 2025
Member
|
@copilot rebase this branch. |
Contributor
Author
Rebased the branch onto origin/main. The rebase completed successfully with no conflicts. The commits now include the latest changes from main (commit b5ab209). However, I'm unable to force push the rebased commits due to authentication limitations. The rebased branch is ready locally with commits:
The branch needs to be force-pushed to origin to update the PR. |
josecelano
approved these changes
Oct 16, 2025
Co-authored-by: josecelano <58816+josecelano@users.noreply.github.com>
…ributors Co-authored-by: josecelano <58816+josecelano@users.noreply.github.com>
… gitignore Co-authored-by: josecelano <58816+josecelano@users.noreply.github.com>
…ory from gitignore Co-authored-by: josecelano <58816+josecelano@users.noreply.github.com>
1d1d60c to
94cb2bc
Compare
Member
|
ACK 94cb2bc |
580f24e
into
3-setup-logging-for-production-cli
22 checks passed
This was referenced Oct 25, 2025
josecelano
added a commit
that referenced
this pull request
Oct 28, 2025
josecelano
added a commit
that referenced
this pull request
Oct 28, 2025
29c3d8d refactor: [#61] standardize method ordering (Proposal #6) (Jose Celano) 7fbc1e6 refactor: [#61] standardize logging patterns (Proposal #5) (Jose Celano) f4b0eb8 refactor: [#61] remove pub(crate) from build_failure_context methods (Proposal #4) (Jose Celano) 99f86a1 refactor: [#61] add help methods to error types (Proposal #3) (Jose Celano) 1bf684a refactor: [#61] extract step execution result type (Proposal #2) (Jose Celano) fb532eb fix: [#61] prevent unnecessary cleanup when infrastructure already destroyed (Jose Celano) 5f77b57 refactor: [#61] extract typed repository wrapper (Proposal #1) (Jose Celano) c946679 refactor: [#61] extract common failure context builder (Proposal #0) (Jose Celano) Pull request description: ## 🎯 Overview This PR completes a comprehensive refactoring of the command handlers codebase to improve maintainability, reduce code duplication, and standardize patterns across all handlers. Closes #61 ## 📋 Changes Summary ### ✅ Completed Proposals (7/7) **Phase 0 - Quick Wins (High Impact, Low Effort)** - ✅ **Proposal #0**: Common failure context builder - Extracted duplicated `build_failure_context` logic into shared helper - ✅ **Proposal #1**: `TypedEnvironmentRepository` wrapper - Created wrapper for type-safe environment state persistence - ✅ **Proposal #2**: `StepResult` type alias - Simplified step execution return types - ✅ **Proposal #3**: Error help methods - Added `.help()` methods to all error types for detailed troubleshooting **Phase 1 - Structural Improvements (High Impact, Medium Effort)** - ✅ **Proposal #4**: Remove `pub(crate)` test exposure - Made internal methods private, deleted tests that tested implementation details **Phase 2 - Consistency & Polish (Medium Impact, Low Effort)** - ✅ **Proposal #5**: Consistent logging patterns - Standardized field naming, simplified logging, added comprehensive documentation - ✅ **Proposal #6**: Standardize method ordering - Reordered methods to follow module organization conventions ## 🔧 Key Improvements ### Code Quality - ✅ Eliminated code duplication in failure context building - ✅ Improved type safety with `TypedEnvironmentRepository` - ✅ Simplified step result types across all handlers - ✅ Consistent method ordering following project conventions ### Developer Experience - ✅ Enhanced error messages with actionable `.help()` methods - ✅ Standardized logging patterns with comprehensive documentation - ✅ All internal implementation details properly encapsulated - ✅ Clear separation between public API and private helpers ### Documentation - ✅ Added "Command Handler Logging Patterns" section to logging guide - ✅ Documented standard patterns with examples for all handlers - ✅ Documented anti-patterns to avoid - ✅ Updated refactoring plan tracking all completed proposals ## 🧪 Testing All quality gates passed: - ✅ **1002 unit tests** - All passing - ✅ **203 integration tests** (doc tests) - All passing - ✅ **45 E2E tests** across all test suites - All passing - ✅ **All linters** passing (markdown, yaml, toml, cspell, clippy, rustfmt, shellcheck) - ✅ **Documentation builds** successfully - ✅ **Zero behavioral changes** - Pure refactoring ### Test Coverage - Unit tests: 1002 passing - Integration tests (AI enforcement): 5 passing - E2E create command: 4 passing - E2E destroy command: 4 passing - Multiprocess file lock: 8 passing - Logging integration: 11 passing - SSH client integration: 9 passing - Template integration: 4 passing ## 📊 Impact ### Before - Duplicated `build_failure_context` across 3 handlers (~90% identical code) - Inconsistent logging patterns (different field names, varying verbosity) - Internal methods exposed as `pub(crate)` for testing - Methods ordered inconsistently across handlers ### After - Single shared `build_failure_context` helper - Consistent logging with standardized field naming (`environment` not `environment_name`) - Proper encapsulation - internal methods are private - Predictable method ordering following module organization conventions ## 🔄 Migration Notes No breaking changes - this is a pure refactoring. All public APIs remain unchanged. ## ✅ Pre-commit Verification ```bash ./scripts/pre-commit.sh ``` **Result**: All checks passed (4m 48s) - ✅ Dependency check (cargo machete) - ✅ All linters (stable & nightly) - ✅ All tests - ✅ Documentation build - ✅ Full E2E test suite ## 📝 Commits 1. `refactor: [#61] extract common failure context builder (Proposal #0)` 2. `refactor: [#61] add TypedEnvironmentRepository wrapper (Proposal #1)` 3. `refactor: [#61] add StepResult type alias (Proposal #2)` 4. `refactor: [#61] add error help methods (Proposal #3)` 5. `refactor: [#61] remove pub(crate) test exposure (Proposal #4)` 6. `refactor: [#61] standardize logging patterns (Proposal #5)` 7. `refactor: [#61] standardize method ordering (Proposal #6)` ## 🎉 Summary This refactoring successfully: - Reduces code duplication - Improves maintainability - Enhances developer experience - Standardizes patterns across all handlers - Maintains 100% backward compatibility Ready for review and merge! 🚀 ACKs for top commit: josecelano: ACK 29c3d8d Tree-SHA512: fa360abfb7519178c4a30e20d61b976dd737fadc15aa4a31d2a801702d9f9d1c1908095c58f4da0d72ef56d7544fdc86ceb67c02a2561eb77ab804764f1cc117
14 tasks
josecelano
added a commit
that referenced
this pull request
Oct 31, 2025
… VMs The 'Allow SSH service by name' task was using a non-existent UFW application profile 'ssh' which caused the playbook to fail before enabling the firewall. This task was redundant because SSH is already explicitly allowed by port number in the previous task. Fixes Issue #4 identified in PR review - UFW fails with 'Could not find a profile matching ssh'
17 tasks
josecelano
added a commit
that referenced
this pull request
Nov 11, 2025
…ollers completion Update documentation in src/presentation/mod.rs to reflect that: - Controllers layer is now complete (Proposal #3 finished) - All commands now use controller pattern consistently - Create command has proper subcommand controller structure - Environment and template controllers are fully implemented - Ready to proceed with Proposal #4 (Views layer reorganization) Also updated re-exports to include all controller error types for better API convenience and consistency.
josecelano
added a commit
that referenced
this pull request
Nov 11, 2025
…ollers completion Update documentation in src/presentation/mod.rs to reflect that: - Controllers layer is now complete (Proposal #3 finished) - All commands now use controller pattern consistently - Create command has proper subcommand controller structure - Environment and template controllers are fully implemented - Ready to proceed with Proposal #4 (Views layer reorganization) Also updated re-exports to include all controller error types for better API convenience and consistency. Fix clippy::doc_markdown warnings by wrapping ExecutionContext in backticks in documentation comments. All linters now pass successfully.
14 tasks
This was referenced Jan 21, 2026
josecelano
added a commit
that referenced
this pull request
Jan 21, 2026
- Created UserInputsError enum with GrafanaRequiresPrometheus, HttpsSectionWithoutTlsServices, TlsServicesWithoutHttpsSection variants - Made UserInputs fields private with getter methods - Changed UserInputs::new() and with_tracker() to return Result - Added cross-service validation in with_tracker(): - Grafana requires Prometheus as data source - HTTPS section requires at least one TLS service - TLS services require HTTPS section for Caddy - Added TrackerConfig::has_any_tls_configured() method - Updated EnvironmentContext::with_working_dir_and_tracker() to return Result - Updated Environment::with_working_dir_and_tracker() to return Result - Added CrossServiceValidation variant to CreateConfigError - Removed duplicate validation from app layer: - GrafanaRequiresPrometheus check from to_environment_params() - TlsWithoutHttpsSection and HttpsSectionWithoutTls error variants - Simplified validate_https_config() to only check admin email - Updated all field access across codebase to use getters - All 1917 tests pass
josecelano
added a commit
that referenced
this pull request
Jan 21, 2026
2ce6c6b refactor: [#281] encapsulate RuntimeOutputs with semantic setters (Jose Celano) 90bc914 refactor: [#281] move EnvironmentParams to domain layer (Jose Celano) f7e342a refactor: [#281] rename Environment constructor to create (Jose Celano) eae2ba6 refactor: [#281] replace to_environment_params with ValidatedEnvironmentParams TryFrom (Jose Celano) 5a28068 docs: [#281] update config README to reflect TryFrom pattern (Jose Celano) 886f2a5 refactor: [#281] replace to_* methods with TryFrom trait for DTO conversions (Jose Celano) 4dd3e37 refactor: [#281] split TrackerServicesView::render into helper methods (Jose Celano) 17903f0 refactor: [#281] simplify ServiceInfo by always computing from tracker config (Jose Celano) 891c818 docs: [#281] mark issue as completed (Jose Celano) 040c38f refactor: [#281] HttpsConfig validated constructor (Proposal #5) (Jose Celano) 07d64de refactor: [#281] UserInputs validated constructor (Proposal #4) (Jose Celano) 7e8174a refactor: [#281] TrackerCoreConfig and DatabaseConfig validation (Proposal #3) (Jose Celano) d8f8b60 refactor: [#281] TrackerConfig validates at construction (Phase 1, Proposal #2) (Jose Celano) 5b2faf3 refactor: [#281] apply validated constructor pattern to tracker config types (Jose Celano) Pull request description: ## Summary Implements the DDD validated constructor pattern for domain types, ensuring invariants are enforced at construction time rather than relying on separate validation calls. Also improves encapsulation across key domain structs. ## Changes ### Phase 0, Proposal 1 (Completed) - Tracker Config Validation Applied the validated constructor pattern to: - **`UdpTrackerConfig`**: Port must be non-zero - **`HttpTrackerConfig`**: Port must be non-zero, TLS requires domain, localhost cannot use TLS - **`HealthCheckApiConfig`**: Port must be non-zero, TLS requires domain, localhost cannot use TLS **Pattern Applied:** - Private fields with getter methods - `::new()` constructors with domain validation - Custom `Deserialize` via serde `deserialize_with` - Domain error types with `help()` method for actionable error messages - `TryFrom<DtoConfig> for DomainConfig` for DTO→Domain conversions ### Phase 0, Proposals 2-6 (Completed) - Core Domain Improvements - **Proposal 2**: `HttpApiConfig` - validated constructor pattern with TLS validation - **Proposal 3**: `HttpApiSection` - `TryFrom` DTO conversion with error propagation - **Proposal 4**: `TrackerSection` - comprehensive `TryFrom` implementation for all nested configs - **Proposal 5**: `ValidatedEnvironmentParams` - replaced 9-element tuple with named struct - **Proposal 6**: `EnvironmentParams` - moved from Application to Domain layer ### Additional Encapsulation (Completed) - **`RuntimeOutputs`**: Made all fields private with semantic setters - `record_provisioning(ip)` - after `provision` command - `record_registration(ip)` - after `register` command - `record_services_started(endpoints)` - after `run` command - Getter methods: `instance_ip()`, `provision_method()`, `service_endpoints()` - Implements `Default` trait ### Files Modified **Domain Layer:** - `src/domain/tracker/config/udp.rs` - Validated constructor pattern - `src/domain/tracker/config/http.rs` - Validated constructor pattern - `src/domain/tracker/config/health_check_api.rs` - Validated constructor pattern - `src/domain/tracker/config/http_api.rs` - Validated constructor pattern - `src/domain/tracker/config/mod.rs` - Updated defaults, tests, helper functions - `src/domain/environment/params.rs` - **NEW** - Moved from Application layer - `src/domain/environment/runtime_outputs.rs` - Encapsulated with semantic setters **Application Layer:** - `*_section.rs` files - Added `TryFrom` implementations - `validated_params.rs` - **NEW** - Named struct replacing tuple - `errors.rs` - Added error variants for invalid configs **Infrastructure Layer:** - Test files updated to use `::new()` constructors and getter methods ## Remaining Work All proposals from Issue #281 are now complete. Additional improvements may include: - [ ] `TrackerConfig` validates at construction (Phase 1) - [ ] `TrackerCoreConfig` database validation (Phase 2) - [ ] `UserInputs` validated constructor (Phase 2) ## Testing - ✅ All lib tests pass - ✅ All doc tests pass - ✅ Pre-commit checks pass (linting, formatting, E2E tests) ## Related Closes #281 ACKs for top commit: josecelano: ACK 2ce6c6b Tree-SHA512: 52453eb56e0082f0f801d801920910e05edb7689df1424c7c442fce304af24ed29f78a642b5bdeba46df63da4e6fbd34325972fa8f5d88bd038551bb05b5db60
josecelano
added a commit
that referenced
this pull request
Feb 16, 2026
…ayer e915c25 docs: mark Proposal 4 as not needed with rationale (Jose Celano) 2ae8339 docs: update refactor plan with Proposal #3 completion (Jose Celano) 68676e1 refactor: separate show command views structure (Proposal #3) (Jose Celano) bd8b95f docs: update refactor plan with Proposal #2 completion (Jose Celano) 6cf2966 refactor: separate list command view from views directory (Proposal #2) (Jose Celano) 52d5560 docs: update refactor plan with Proposal #1 completion (Jose Celano) 6539e78 refactor: separate provision command view data from views (Proposal #1) (Jose Celano) c1093f5 docs: update refactor plan with Proposal #0 completion (Jose Celano) 9a52ddc refactor: separate create command view data from views (Proposal #0) (Jose Celano) Pull request description: ## Overview This refactoring establishes a clear separation between view data structures (DTOs) and view rendering logic in the presentation layer. It creates a consistent, scalable structure for all command views as a prerequisite for implementing JSON output support (EPIC #348 tasks 12.3-12.5). ## Changes Summary ### Implemented Proposals (4/5) **✅ Proposal #0: Create Command** (Commit: 9a52ddc) - Separated `environment_details.rs` into `view_data/` subdirectory - Moved `text_view.rs` and `json_view.rs` into `views/` subdirectory - Updated module structure with proper re-exports **✅ Proposal #1: Provision Command** (Commit: 6539e78) - Organized 3 DTOs in `view_data/` (provision_details, connection_details, dns_reminder) - Organized 2 views in `views/` (text_view, json_view) - Updated comprehensive module structure **✅ Proposal #2: List Command** (Commit: 6cf2966) - Moved and renamed `environment_list.rs` to `views/text_view.rs` - Renamed `EnvironmentListView` to `TextView` throughout - Updated controller imports **✅ Proposal #3: Show Command** (Commit: 68676e1) - Renamed `environment_info/` directory to `views/` - Renamed `EnvironmentInfoView` to `TextView` - Organized 8 helper view files in consistent structure **❌ Proposal #4: Shared Components** (Discarded - Not Needed) - Analyzed `shared/service_urls/` components - Determined current structure is optimal - No changes required - clear naming, pure view helpers, well-organized ## Directory Structure Achieved ```rust src/presentation/views/commands/ ├── create/ │ ├── view_data/environment_details.rs (DTO) │ └── views/text_view.rs, json_view.rs (Views) ├── provision/ │ ├── view_data/provision_details.rs, ... (DTOs) │ └── views/text_view.rs, json_view.rs (Views) ├── list/ │ └── views/text_view.rs (View only) ├── show/ │ └── views/mod.rs, basic.rs, ... (Views only) └── shared/ └── service_urls/ (No change - already optimal) ``` ## Testing & Quality Assurance - ✅ All 2238 tests passing (5 ignored) - ✅ All linters passing (markdown, yaml, toml, cspell, clippy, rustfmt, shellcheck) - ✅ No unused dependencies (cargo machete) - ✅ Module-level documentation updated - ✅ 9 commits with clean history ## Benefits - **Consistency**: All commands now follow the Strategy Pattern with clear DTO + View separation where applicable - **Scalability**: Easy to add JSON views to remaining commands (show, run, list) - **Discoverability**: Clear directory structure makes it obvious where new code belongs - **Maintainability**: Consistent patterns reduce cognitive load for contributors ## Related Documentation - [Refactor Plan](docs/refactors/plans/separate-view-data-from-views.md) - Status: ✅ Complete - [EPIC #348](#348) - Add JSON Output Format Support - [Issue #352](#352) - Add JSON output to provision command ✅ - [Issue #349](#349) - Add JSON output to create command ✅ ## Next Steps This refactoring provides the foundation for EPIC #348 tasks 12.3-12.5: - Add JSON output to `show` command - Add JSON output to `run` command - Add JSON output to `list` command --- **Branch**: `refactor/separate-view-data-from-views` **Commits**: 9 total (8 implementation + 1 plan update) **Status**: Ready for review ACKs for top commit: josecelano: ACK e915c25 Tree-SHA512: 30baafda202db2e5a3b84fdc216d5aec15eba0d2b620236297ac875ba1b8ff76707625973571c0f504033cb5a0fc04e7b0ad06b7f3eb5754385fa157999ea7c2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Setup Logging for Production CLI ✅
Complete implementation of CLI logging initialization for the main application binary.
Implementation Checklist - ALL COMPLETE ✅
Phase 1: Basic CLI Structure ✅
src/app.rsmodule with CLI struct and run() functionsrc/main.rsto call app::run()Phase 2: Argument Validation ✅
Phase 3: Documentation ✅
docs/user-guide/logging.mdfor end usersdocs/contributing/logging-guide.mdfor contributorsPhase 4: Integration Testing ✅
Phase 5: Final Validation ✅
cargo run --bin linter all)Summary of Changes
Code Changes
Created
src/app.rs- Main application module with CLI structure:--log-format: pretty, json, or compact (default: compact)--log-output: file-only or file-and-stderr (default: file-only)--log-dir: path to log directory (default: ./data/logs)Updated
src/main.rs- Minimal entry point:app::run()Code Quality:
Documentation Changes
README.md - Simplified logging section:
docs/user-guide/logging.md- Complete user guide (380+ lines):docs/contributing/logging-guide.md- Updated contributor guide:.gitignore- Cleaned up:custom-logs/)Testing Results
Linting ✅
Manual Testing ✅
Default Configuration:
Format Options:
Output Modes:
Custom Log Directories:
RUST_LOG Environment Variable:
Log File Persistence:
Error Handling:
Help and Version:
Acceptance Criteria - ALL MET ✅
Functional Requirements ✅
--log-format,--log-output,--log-dir)RUST_LOGenvironment variable is respectedCode Quality ✅
cargo run --bin linter all)Documentation ✅
docs/user-guide/logging.mddocs/contributing/logging-guide.md--help) is clear and comprehensiveUser Experience ✅
Key Features
Production-Safe Defaults
./data/logs/log.txtFlexible Configuration
Observability
Developer Experience
Related Documentation
Issue: #3 - Setup logging for production CLI
Estimated Effort: 4-5 hours
Actual Effort: ~4 hours
Status: ✅ Complete - All phases finished, all tests passing, fully documented
Original prompt
Fixes #3
💬 Share your feedback on Copilot coding agent for the chance to win a $200 gift card! Click here to start the survey.