Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 18 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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::{
Expand Down Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions src/checkable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
41 changes: 34 additions & 7 deletions src/common/extraction/graph_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -59,7 +59,7 @@ pub fn extract_graph(
project: &CargoProject,
source_options: SourceOptions,
) -> Result<GraphExtraction, ArchUnitError> {
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.
Expand All @@ -71,7 +71,34 @@ pub fn extract_graph_with_options(
options: &CheckOptions,
) -> Result<GraphExtraction, ArchUnitError> {
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.
Expand All @@ -88,15 +115,15 @@ fn extract_graph_cached(
project: &CargoProject,
source_options: SourceOptions,
clear_before: bool,
) -> Result<GraphExtraction, ArchUnitError> {
) -> Result<(GraphExtraction, bool), ArchUnitError> {
if clear_before {
clear_graph_cache()?;
}
let key = build_graph_cache_key(project, source_options);
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
};
Expand All @@ -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 {
Expand Down
20 changes: 20 additions & 0 deletions src/common/logging/check_logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<S: AsRef<str>>(
&self,
context: &str,
subjects: impl IntoIterator<Item = S>,
) -> 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`]
Expand Down
32 changes: 31 additions & 1 deletion src/common/logging/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,19 +80,49 @@ 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)
)
}
}

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(
Expand Down
86 changes: 82 additions & 4 deletions src/common/logging/options.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::{
fmt,
fs::{self, OpenOptions},
io::Write,
io::{IsTerminal, Write},
path::{Path, PathBuf},
process,
sync::{Arc, Mutex},
Expand Down Expand Up @@ -42,6 +42,7 @@ struct FileOutput {
pub struct LoggingOptions {
level: LogLevel,
console_output: bool,
console_color: bool,
file_mode: LogFileMode,
file_output: Option<FileOutput>,
}
Expand All @@ -53,6 +54,7 @@ impl LoggingOptions {
Self {
level: LogLevel::Info,
console_output: true,
console_color: false,
file_mode: LogFileMode::Append,
file_output: None,
}
Expand All @@ -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<Path>) -> Self {
Expand Down Expand Up @@ -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)?;
Expand All @@ -165,15 +175,43 @@ 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()
}
}

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()),
Expand Down Expand Up @@ -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'));
}
}
}
1 change: 1 addition & 0 deletions src/files/fluentapi/custom_file_condition.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand Down
1 change: 1 addition & 0 deletions src/files/fluentapi/cycle_free_file_condition.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
1 change: 1 addition & 0 deletions src/files/fluentapi/depend_on_external_module_condition.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
1 change: 1 addition & 0 deletions src/files/fluentapi/depend_on_file_condition.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
1 change: 1 addition & 0 deletions src/files/fluentapi/match_pattern_file_condition.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand Down
Loading
Loading