diff --git a/README.md b/README.md index 98e07f6..8c6d91a 100644 --- a/README.md +++ b/README.md @@ -296,11 +296,10 @@ snapshot. `MetricsExporter` also renders or writes a `MetricsReportData` map dir no scripts or network dependencies; names, values, and titles are HTML-escaped. Timestamps are UTC and can be disabled for byte-stable build artifacts. Custom CSS replaces the built-in stylesheet. -## Per-check logging +## Detailed inspection and readable output Checks are quiet by default. Logging is enabled only by putting a `LoggingOptions` value into the -`CheckOptions` passed to that check; the crate never reads a global logger or an environment -variable: +`CheckOptions` passed to that check; the crate never configures a global logger: ```rust,no_run use archunit::{ @@ -331,12 +330,26 @@ fn check_boundaries() -> Result<(), ArchUnitError> { } ``` -`LoggingOptions::new()` logs at `Info` level to the console. `Debug` adds progress and metric -records; violations and failed verdicts use `Warn`, while execution errors use `Error`. The fixed +`LoggingOptions::new()` logs at `Info` level to the console. `Debug` is the fullest inspection +level: cache hit/miss and source options, every discovered file and resolved dependency, extraction +diagnostics, selected files/layers/slices, metric values and thresholds, and violation details. +Graph reports also log their query, selected nodes, aggregated edges, and summary. `Info` shows +check boundaries; violations and failed verdicts use `Warn`, while execution errors use `Error`. The fixed event vocabulary is `start check`, `end check`, `log progress`, `log violation`, and `log metric`. Ordinary `debug`, `info`, `warn`, and `error` records are also available through `CheckLogger` for custom `Checkable` implementations. +For a highlighted terminal transcript, add `.with_console_color(true)` to the logging options. +Debug is cyan, info green, warnings yellow, and errors red. ANSI requires an explicit request and an interactive console, respects `NO_COLOR` and `CI`, +and never appears in redirected output or log files. Debug inspection reads the graph and selected values already used by the +check; it does not rerun predicates or change violations. Logging I/O failures retain their +existing error behavior. + +For test failures, `ResultFactory` already assembles numbered, indented explanations with +selectors, dependency evidence, cycles, and metric values. Use +`TestResultOptions::new().with_color(ColorChoice::Always)` for ANSI highlighting, +`ColorChoice::Never` for plain CI artifacts, or the default `Auto`. + File output creates missing directories and chooses a collision-resistant, UTC-timestamped `.log` filename. `file_path()` exposes that path before execution so CI can archive it. `Append` preserves an existing file; `Overwrite` truncates it once before the first record. Clones of one configuration diff --git a/src/checkable.rs b/src/checkable.rs index a44aebb..e02e482 100644 --- a/src/checkable.rs +++ b/src/checkable.rs @@ -27,6 +27,9 @@ where Ok(violations) => { for violation in &violations { logger.log_violation(violation.kind().as_str())?; + if logger.is_enabled_for(crate::common::LogLevel::Debug) { + logger.log_progress(format!("violation details: {violation:?}"))?; + } } logger.end_check(rule_name, violations.len())?; Ok(violations) diff --git a/src/common/extraction/graph_cache.rs b/src/common/extraction/graph_cache.rs index 356bf90..adbdfb8 100644 --- a/src/common/extraction/graph_cache.rs +++ b/src/common/extraction/graph_cache.rs @@ -7,7 +7,7 @@ use super::{ CargoProject, DEFAULT_EXCLUDED_DIRECTORIES, GraphExtraction, SourceOptions, extract_graph::extract_graph_uncached, }; -use crate::common::{ArchUnitError, CheckOptions, TechnicalError}; +use crate::common::{ArchUnitError, CheckLogger, CheckOptions, LogLevel, TechnicalError}; const CFG_POLICY: &str = "conservative-union"; const FEATURE_POLICY: &str = "cargo-metadata-declarations"; @@ -59,7 +59,7 @@ pub fn extract_graph( project: &CargoProject, source_options: SourceOptions, ) -> Result { - extract_graph_cached(project, source_options, false) + extract_graph_cached(project, source_options, false).map(|(extraction, _)| extraction) } /// Extracts a graph using the extraction-related settings from one architecture check. @@ -71,7 +71,34 @@ pub fn extract_graph_with_options( options: &CheckOptions, ) -> Result { let source_options = SourceOptions::new().with_dev_targets(options.includes_test_sources()); - extract_graph_cached(project, source_options, options.clears_cache()) + let logger = CheckLogger::new(options.logging()); + logger.validate()?; + let (extraction, cached) = + extract_graph_cached(project, source_options, options.clears_cache())?; + if logger.is_enabled_for(LogLevel::Debug) { + logger.log_progress(format!( + "graph cache={}; clear requested={}; include test sources={}", + if cached { "hit" } else { "miss" }, + options.clears_cache(), + options.includes_test_sources(), + ))?; + logger.log_progress(format!( + "extracted edges={}; diagnostics={}", + extraction.graph().edges().len(), + extraction.diagnostics().len() + ))?; + for edge in extraction.graph().edges() { + if edge.is_self_edge() { + logger.log_progress(format!("discovered file: {}", edge.source))?; + } else { + logger.log_progress(format!("dependency: {edge}"))?; + } + } + for diagnostic in extraction.diagnostics() { + logger.log_progress(format!("extraction diagnostic: {diagnostic:?}"))?; + } + } + Ok(extraction) } /// Clears every memoized graph and its diagnostics in the current process. @@ -88,7 +115,7 @@ fn extract_graph_cached( project: &CargoProject, source_options: SourceOptions, clear_before: bool, -) -> Result { +) -> Result<(GraphExtraction, bool), ArchUnitError> { if clear_before { clear_graph_cache()?; } @@ -96,7 +123,7 @@ fn extract_graph_cached( let generation = { let cache = graph_cache().read().map_err(|_| cache_lock_error("read"))?; if let Some(extraction) = cache.entries.get(&key) { - return Ok(extraction.clone()); + return Ok((extraction.clone(), true)); } cache.generation }; @@ -106,9 +133,9 @@ fn extract_graph_cached( .write() .map_err(|_| cache_lock_error("write"))?; if cache.generation != generation { - return Ok(extracted); + return Ok((extracted, false)); } - Ok(cache.entries.entry(key).or_insert(extracted).clone()) + Ok((cache.entries.entry(key).or_insert(extracted).clone(), false)) } fn cache_lock_error(operation: &str) -> ArchUnitError { diff --git a/src/common/logging/check_logger.rs b/src/common/logging/check_logger.rs index 0e01645..9718e7c 100644 --- a/src/common/logging/check_logger.rs +++ b/src/common/logging/check_logger.rs @@ -22,6 +22,26 @@ impl<'a> CheckLogger<'a> { self.options.is_some() } + /// Returns whether a severity is enabled before preparing expensive inspection details. + #[must_use] + pub fn is_enabled_for(&self, level: LogLevel) -> bool { + self.options.is_some_and(|options| options.accepts(level)) + } + + /// Logs each selected subject at debug level without evaluating the iterator when disabled. + pub fn log_subjects>( + &self, + context: &str, + subjects: impl IntoIterator, + ) -> Result<(), ArchUnitError> { + if self.is_enabled_for(LogLevel::Debug) { + for subject in subjects { + self.log_progress(format!("{context}: {}", subject.as_ref()))?; + } + } + Ok(()) + } + /// Validates the explicitly configured sinks without emitting a record. /// /// Built-in architecture checks call this before project discovery. Custom [`crate::Checkable`] diff --git a/src/common/logging/event.rs b/src/common/logging/event.rs index 06d4ef2..909a7ce 100644 --- a/src/common/logging/event.rs +++ b/src/common/logging/event.rs @@ -80,7 +80,12 @@ impl LogRecord { /// Renders the deterministic destination-neutral record. #[must_use] pub fn render(&self) -> String { - format!("[{}] {}: {}", self.level, self.event.as_str(), self.message) + format!( + "[{}] {}: {}", + self.level, + self.event.as_str(), + render_message(&self.message) + ) } } @@ -88,11 +93,36 @@ fn sanitize_message(message: &str) -> String { message.replace('\r', "\\r").replace('\n', "\\n") } +fn render_message(message: &str) -> String { + let mut safe = String::new(); + for character in message.chars() { + if character.is_control() { + safe.push_str(&character.escape_default().to_string()); + } else { + safe.push(character); + } + } + safe +} + #[cfg(test)] mod tests { use super::{LogEventKind, LogRecord}; use crate::common::LogLevel; + #[test] + fn control_characters_cannot_inject_terminal_formatting() { + let record = LogRecord::new( + LogLevel::Debug, + LogEventKind::Progress, + "src/\x1b[31mfile.rs\t", + ); + assert!(record.message().contains('\x1b')); + assert!(!record.render().contains('\x1b')); + assert!(!record.render().contains('\t')); + assert!(record.render().contains("file.rs")); + } + #[test] fn records_use_the_fixed_vocabulary_and_remain_one_line() { let record = LogRecord::new( diff --git a/src/common/logging/options.rs b/src/common/logging/options.rs index 512a6e7..ce1de28 100644 --- a/src/common/logging/options.rs +++ b/src/common/logging/options.rs @@ -1,7 +1,7 @@ use std::{ fmt, fs::{self, OpenOptions}, - io::Write, + io::{IsTerminal, Write}, path::{Path, PathBuf}, process, sync::{Arc, Mutex}, @@ -42,6 +42,7 @@ struct FileOutput { pub struct LoggingOptions { level: LogLevel, console_output: bool, + console_color: bool, file_mode: LogFileMode, file_output: Option, } @@ -53,6 +54,7 @@ impl LoggingOptions { Self { level: LogLevel::Info, console_output: true, + console_color: false, file_mode: LogFileMode::Append, file_output: None, } @@ -72,6 +74,14 @@ impl LoggingOptions { self } + /// Requests ANSI severity highlighting on interactive consoles outside CI/NO_COLOR. + /// File records always stay plain. + #[must_use] + pub const fn with_console_color(mut self, enabled: bool) -> Self { + self.console_color = enabled; + self + } + /// Enables file output under `directory` with an automatically timestamped `.log` filename. #[must_use] pub fn with_file_output(mut self, directory: impl AsRef) -> Self { @@ -146,7 +156,7 @@ impl LoggingOptions { pub(super) fn write(&self, record: &LogRecord) -> Result<(), ArchUnitError> { self.validate()?; if self.console_output { - write_console(record)?; + write_console(record, self.console_color)?; } if let Some(output) = &self.file_output { write_file(output, self.file_mode, record)?; @@ -165,6 +175,7 @@ impl PartialEq for LoggingOptions { fn eq(&self, other: &Self) -> bool { self.level == other.level && self.console_output == other.console_output + && self.console_color == other.console_color && self.file_mode == other.file_mode && self.file_path() == other.file_path() } @@ -172,8 +183,35 @@ impl PartialEq for LoggingOptions { impl Eq for LoggingOptions {} -fn write_console(record: &LogRecord) -> Result<(), ArchUnitError> { - let rendered = format!("{}\n", record.render()); +fn render_console(record: &LogRecord, color: bool) -> String { + if !color { + return format!("{}\n", record.render()); + } + let code = match record.level() { + LogLevel::Debug => "36", + LogLevel::Info => "32", + LogLevel::Warn => "33", + LogLevel::Error => "31", + }; + format!("\x1b[{code}m{}\x1b[0m\n", record.render()) +} + +fn console_color_allowed(requested: bool, terminal: bool, no_color: bool, ci: bool) -> bool { + requested && terminal && !no_color && !ci +} + +fn write_console(record: &LogRecord, color: bool) -> Result<(), ArchUnitError> { + let terminal = match record.level() { + LogLevel::Warn | LogLevel::Error => std::io::stderr().is_terminal(), + LogLevel::Debug | LogLevel::Info => std::io::stdout().is_terminal(), + }; + let color = console_color_allowed( + color, + terminal, + std::env::var_os("NO_COLOR").is_some(), + std::env::var_os("CI").is_some(), + ); + let rendered = render_console(record, color); let result = match record.level() { LogLevel::Warn | LogLevel::Error => std::io::stderr().lock().write_all(rendered.as_bytes()), LogLevel::Debug | LogLevel::Info => std::io::stdout().lock().write_all(rendered.as_bytes()), @@ -488,3 +526,43 @@ mod tests { fs::remove_dir_all(directory).expect("temporary logging tree should be removable"); } } + +#[cfg(test)] +mod console_color_tests { + use super::{console_color_allowed, render_console}; + use crate::common::{LogEventKind, LogLevel, LogRecord}; + + #[test] + fn console_color_requires_an_explicit_interactive_request_outside_ci() { + assert!(console_color_allowed(true, true, false, false)); + for (request, terminal, no_color, ci) in [ + (false, true, false, false), + (true, false, false, false), + (true, true, true, false), + (true, true, false, true), + ] { + assert!(!console_color_allowed(request, terminal, no_color, ci)); + } + } + + #[test] + fn ansi_is_explicit_and_does_not_change_the_destination_neutral_record() { + for (level, code) in [ + (LogLevel::Debug, "36"), + (LogLevel::Info, "32"), + (LogLevel::Warn, "33"), + (LogLevel::Error, "31"), + ] { + let record = LogRecord::new(level, LogEventKind::Progress, "subject"); + assert_eq!( + render_console(&record, false), + format!("{}\n", record.render()) + ); + assert_eq!( + render_console(&record, true), + format!("\x1b[{code}m{}\x1b[0m\n", record.render()) + ); + assert!(!record.render().contains('\x1b')); + } + } +} diff --git a/src/files/fluentapi/custom_file_condition.rs b/src/files/fluentapi/custom_file_condition.rs index 76e6be1..6d15891 100644 --- a/src/files/fluentapi/custom_file_condition.rs +++ b/src/files/fluentapi/custom_file_condition.rs @@ -112,6 +112,7 @@ impl Checkable for CustomFileCondition { let extraction = extract_graph_with_options(&project, options)?; let selected = selected_nodes(extraction.graph(), self.filters()); logger.log_progress(format!("selected files={}", selected.len()))?; + logger.log_subjects("selected file", selected.iter().map(|node| &node.label))?; if let Some(violation) = empty_selection_violation(&selected, self.filters(), self.is_negated(), options) { diff --git a/src/files/fluentapi/cycle_free_file_condition.rs b/src/files/fluentapi/cycle_free_file_condition.rs index c51d3a3..fb41de2 100644 --- a/src/files/fluentapi/cycle_free_file_condition.rs +++ b/src/files/fluentapi/cycle_free_file_condition.rs @@ -84,6 +84,7 @@ impl Checkable for CycleFreeFileCondition { let extraction = extract_graph_with_options(&project, options)?; let selected = selected_nodes(extraction.graph(), self.filters()); logger.log_progress(format!("selected files={}", selected.len()))?; + logger.log_subjects("selected file", selected.iter().map(|node| &node.label))?; if let Some(violation) = empty_selection_violation( &selected, self.filters(), diff --git a/src/files/fluentapi/depend_on_external_module_condition.rs b/src/files/fluentapi/depend_on_external_module_condition.rs index a4245de..f2265be 100644 --- a/src/files/fluentapi/depend_on_external_module_condition.rs +++ b/src/files/fluentapi/depend_on_external_module_condition.rs @@ -117,6 +117,7 @@ impl Checkable for DependOnExternalModuleCondition { let extraction = extract_graph_with_options(&project, options)?; let selected = selected_nodes(extraction.graph(), self.subject_filters()); logger.log_progress(format!("selected files={}", selected.len()))?; + logger.log_subjects("selected file", selected.iter().map(|node| &node.label))?; if let Some(violation) = empty_selection_violation( &selected, self.subject_filters(), diff --git a/src/files/fluentapi/depend_on_file_condition.rs b/src/files/fluentapi/depend_on_file_condition.rs index ee60e3b..26070a0 100644 --- a/src/files/fluentapi/depend_on_file_condition.rs +++ b/src/files/fluentapi/depend_on_file_condition.rs @@ -127,6 +127,7 @@ impl Checkable for DependOnFileCondition { let extraction = extract_graph_with_options(&project, options)?; let selected = selected_nodes(extraction.graph(), self.subject_filters()); logger.log_progress(format!("selected files={}", selected.len()))?; + logger.log_subjects("selected file", selected.iter().map(|node| &node.label))?; if let Some(violation) = empty_selection_violation( &selected, self.subject_filters(), diff --git a/src/files/fluentapi/match_pattern_file_condition.rs b/src/files/fluentapi/match_pattern_file_condition.rs index 1bda95d..bc667b9 100644 --- a/src/files/fluentapi/match_pattern_file_condition.rs +++ b/src/files/fluentapi/match_pattern_file_condition.rs @@ -88,6 +88,7 @@ impl Checkable for MatchPatternFileCondition { let extraction = extract_graph_with_options(&project, options)?; let selected = selected_nodes(extraction.graph(), self.filters()); logger.log_progress(format!("selected files={}", selected.len()))?; + logger.log_subjects("selected file", selected.iter().map(|node| &node.label))?; if let Some(violation) = empty_selection_violation(&selected, self.filters(), self.is_negated(), options) { diff --git a/src/graph/fluentapi/project_graph_builder.rs b/src/graph/fluentapi/project_graph_builder.rs index f23dd33..a62fe0a 100644 --- a/src/graph/fluentapi/project_graph_builder.rs +++ b/src/graph/fluentapi/project_graph_builder.rs @@ -2,8 +2,8 @@ use std::path::Path; use crate::{ common::{ - ArchUnitError, CheckOptions, PatternError, ProjectLocator, RegexFactory, UserError, - extract_graph_with_options, locate_project_from, + ArchUnitError, CheckLogger, CheckOptions, LogLevel, PatternError, ProjectLocator, + RegexFactory, UserError, extract_graph_with_options, locate_project_from, }, graph::{ FolderDepthCollapse, GraphCollapse, GraphQueryError, GraphQueryOptions, GraphRenderer, @@ -135,9 +135,42 @@ impl ProjectGraphBuilder { return Err(configuration_error(error.clone())); } + let logger = CheckLogger::new(self.check_options.logging()); + logger.validate()?; + logger.start_check("graph.snapshot")?; + let result = self.snapshot_logged(&logger); + match result { + Ok(snapshot) => { + logger.end_check("graph.snapshot", 0)?; + Ok(snapshot) + } + Err(error) => { + let _ = logger.error(format!("graph.snapshot: {error}")); + Err(error) + } + } + } + + fn snapshot_logged( + &self, + logger: &CheckLogger<'_>, + ) -> Result { let project = locate_project_from(self.project_locator())?; let extraction = extract_graph_with_options(&project, self.check_options())?; - create_graph_snapshot(extraction.graph(), self.options()).map_err(configuration_error) + let snapshot = create_graph_snapshot(extraction.graph(), self.options()) + .map_err(configuration_error)?; + if logger.is_enabled_for(LogLevel::Debug) { + logger.log_progress(format!("graph query: {:?}", self.options()))?; + logger.log_progress(format!("graph summary: {:?}", snapshot.summary))?; + logger.log_subjects("report node", snapshot.nodes.iter().map(|node| &node.label))?; + for edge in &snapshot.edges { + logger.log_progress(format!( + "report dependency: {} -> {}; count={}; external={}; kinds={}", + edge.source, edge.target, edge.count, edge.external, edge.import_kinds + ))?; + } + } + Ok(snapshot) } /// Extracts the project and returns only the queried snapshot counts. diff --git a/src/layers/fluentapi/layered_architecture.rs b/src/layers/fluentapi/layered_architecture.rs index b041071..a220765 100644 --- a/src/layers/fluentapi/layered_architecture.rs +++ b/src/layers/fluentapi/layered_architecture.rs @@ -266,6 +266,7 @@ impl Checkable for LayeredArchitecture { "layer {source_layer}; selected files={}", selected.len() ))?; + logger.log_subjects(source_layer, selected.iter().map(|node| &node.label))?; violations.extend( gather_empty_test_violations( &selected, diff --git a/src/slices/fluentapi/diagram_slice_condition.rs b/src/slices/fluentapi/diagram_slice_condition.rs index 1653c4a..8cd02ab 100644 --- a/src/slices/fluentapi/diagram_slice_condition.rs +++ b/src/slices/fluentapi/diagram_slice_condition.rs @@ -89,6 +89,7 @@ impl Checkable for DiagramSliceCondition { let graph = extraction.graph(); let labels = self.projection().slice_labels(graph); logger.log_progress(format!("selected slices={}", labels.len()))?; + logger.log_subjects("selected slice", &labels)?; let empty = gather_empty_test_violations( &labels, "slices", diff --git a/src/slices/fluentapi/forbidden_slice_dependency_condition.rs b/src/slices/fluentapi/forbidden_slice_dependency_condition.rs index 2289ea4..0d8d4fd 100644 --- a/src/slices/fluentapi/forbidden_slice_dependency_condition.rs +++ b/src/slices/fluentapi/forbidden_slice_dependency_condition.rs @@ -92,6 +92,7 @@ impl Checkable for ForbiddenSliceDependencyCondition { let graph = extraction.graph(); let labels = self.projection().slice_labels(graph); logger.log_progress(format!("selected slices={}", labels.len()))?; + logger.log_subjects("selected slice", &labels)?; let empty = gather_empty_test_violations( &labels, "slices", diff --git a/tests/public_logging.rs b/tests/public_logging.rs index 98a71eb..b476dff 100644 --- a/tests/public_logging.rs +++ b/tests/public_logging.rs @@ -187,3 +187,74 @@ fn invalid_logging_configuration_precedes_rule_io_and_is_typed() { assert!(!error.to_string().contains("Cargo")); } } + +#[test] +fn debug_inspection_preserves_rule_results_and_graph_snapshots() { + let output = TemporaryDirectory::new("inspection"); + let logging = LoggingOptions::new() + .with_level(LogLevel::Debug) + .with_console_output(false) + .with_console_color(true) + .with_file_output(output.path()); + let path = logging.file_path().expect("file sink").to_path_buf(); + let options = CheckOptions::new().with_logging(logging); + let rule = project_files_in(fixture("layered_project")) + .in_file("src/api/mod.rs") + .should() + .have_name("wrong.rs"); + assert_eq!( + format!("{:?}", rule.check().expect("quiet rule")), + format!("{:?}", rule.check_with(&options).expect("logged rule")) + ); + let graph = archunit::project_graph_in(fixture("layered_project")).focus_on("src/api/**", 1); + let expected = graph.snapshot().expect("quiet snapshot"); + assert_eq!( + expected, + graph + .with_check_options(options) + .snapshot() + .expect("logged snapshot") + ); + let content = fs::read_to_string(path).expect("read inspection log"); + for detail in [ + "graph cache=", + "discovered file: src/api/mod.rs", + "dependency:", + "selected file: src/api/mod.rs", + "violation details:", + "start check: graph.snapshot", + "graph query:", + "graph summary:", + "report node:", + "report dependency:", + "end check: graph.snapshot; violations=0", + ] { + assert!(content.contains(detail), "missing {detail}"); + } + assert!(!content.contains('\x1b'), "file logs must remain plain"); +} + +#[test] +fn non_debug_levels_filter_inspection_without_changing_violations() { + let rule = project_files_in(fixture("layered_project")) + .in_file("src/api/mod.rs") + .should() + .have_name("wrong.rs"); + let expected = rule.check().expect("quiet rule"); + for level in [LogLevel::Info, LogLevel::Warn, LogLevel::Error] { + let output = TemporaryDirectory::new("filtered"); + let logging = LoggingOptions::new() + .with_level(level) + .with_console_output(false) + .with_file_output(output.path()); + let path = logging.file_path().expect("file sink").to_path_buf(); + let actual = rule + .check_with(&CheckOptions::new().with_logging(logging)) + .expect("logged rule"); + assert_eq!(format!("{actual:?}"), format!("{expected:?}")); + let content = fs::read_to_string(path).unwrap_or_default(); + assert!(!content.contains("[DEBUG]")); + assert_eq!(content.contains("start check"), level == LogLevel::Info); + assert_eq!(content.contains("log violation"), level != LogLevel::Error); + } +}