From 1b9f7d05d3620dc44fa48220c53b6829414b8b69 Mon Sep 17 00:00:00 2001 From: Lukas Niessen Date: Wed, 30 Sep 2026 18:04:03 +0200 Subject: [PATCH 1/3] Add debug graph and selection inspection with report examples --- README.md | 53 +++++++++++++++++++ common/logging/inspection.go | 48 +++++++++++++++++ common/logging/inspection_test.go | 48 +++++++++++++++++ common/logging/logger.go | 2 +- files/fluentapi/adhere_to.go | 7 +-- files/fluentapi/depend_on_external_modules.go | 3 ++ files/fluentapi/depend_on_files.go | 3 ++ files/fluentapi/have_no_cycles.go | 2 + files/fluentapi/logged_progress_test.go | 29 ++++++++++ files/fluentapi/naming_condition.go | 6 +-- layers/fluentapi/policy_condition.go | 2 + metrics/fluentapi/metrics.go | 11 +++- metrics/fluentapi/should_be.go | 2 +- metrics/fluentapi/should_satisfy.go | 2 +- metrics/fluentapi/zone_checks.go | 2 +- slices/fluentapi/adhere_to_diagram.go | 2 + slices/fluentapi/contain_dependency.go | 2 + 17 files changed, 213 insertions(+), 11 deletions(-) create mode 100644 common/logging/inspection.go create mode 100644 common/logging/inspection_test.go diff --git a/README.md b/README.md index a859cb0..994c9eb 100644 --- a/README.md +++ b/README.md @@ -423,6 +423,59 @@ holds the file a CI job archives, and the four levels are `LogLevelDebug`, `LogL default), `LogLevelWarn` and `LogLevelError`. A technical failure is still the error `Check` returns; a log line is never how this library reports something. +### Detailed inspection + +`LogLevelDebug` shows each extracted file and dependency, import kinds and external targets, +selected source/target files, layer and slice membership, progress counts, metric measurements, +violations, and the outcome. It observes the graph used by the check, including cached graphs, +without repeating custom calculations. + +```go +violations, err := rule.Check(&archunit.CheckOptions{ + Logging: &archunit.LogOptions{ + Writer: os.Stderr, + Level: archunit.LogLevelDebug, + File: "build/archunit.log", + }, +}) +``` + +| Level | Included output | +| --- | --- | +| `LogLevelDebug` | Graph inspection, selections, progress, and everything below | +| `LogLevelInfo` | Check start/end, metric measurements, warnings and errors | +| `LogLevelWarn` | Violations and technical failures | +| `LogLevelError` | Technical failures | + +Example debug lines: + +```text +debug inspect: discovered file: "internal/api/handler.go" +debug inspect: selected file: "internal/api/handler.go" +debug progress: selected files: 1 +``` + +`Writer` and `File` can be used together; omit `Writer` for file-only logging. Files append unless +`Overwrite` is true. `Timestamp` adds a caller-supplied timestamp to the filename. Archive the log +as a CI artifact. A requested log that cannot be opened, written, or closed still returns a +technical error. No destination means no output or file creation. + +### Readable, colored failure reports + +Numbered violations retain the source, requirement, and dependency or metric evidence. Enable +the existing semantic palette when displaying them in a terminal: + +```go +report := archunit.NewResultFactory(&archunit.MessageOptions{ + Palette: archunit.DefaultPalette(), +}).Result(violations) +fmt.Println(report.Message) +``` + +Failures are red, subjects cyan, requirements yellow, and successful results green. Omit the +palette for plain text in CI logs and artifacts. `MaxViolations` limits a long report and its +footer states how many violations were omitted. Formatting leaves returned violations unchanged. + ## 🚫 Keeping One Import Out of the Graph Some imports are not dependencies. The directive is written the way Go writes a machine-readable diff --git a/common/logging/inspection.go b/common/logging/inspection.go new file mode 100644 index 0000000..7ea8987 --- /dev/null +++ b/common/logging/inspection.go @@ -0,0 +1,48 @@ +package logging + +import ( + "fmt" + "maps" + "slices" + "strconv" + + "github.com/LukasNiessen/ArchUnitGo/common/extraction" +) + +// LogGraph records every discovered file and dependency at debug level, including +// external targets and import kinds. It does not re-extract or change the graph. +func (l *Logger) LogGraph(graph extraction.Graph) { + if !l.enabled(LevelDebug) { + return + } + for _, edge := range graph { + if edge.IsSelfEdge() { + l.record(LevelDebug, "inspect", "discovered file: "+strconv.Quote(edge.Source)) + continue + } + l.record(LevelDebug, "inspect", fmt.Sprintf("dependency: %q -> %q (external=%t, kinds=%s)", + edge.Source, edge.Target, edge.External, edge.ImportKinds)) + } +} + +// LogSelection records the members of one selection at debug level. It preserves +// the caller's order and quotes identifiers so control characters cannot add lines. +func (l *Logger) LogSelection(step string, identifiers []string) { + if !l.enabled(LevelDebug) { + return + } + for _, identifier := range identifiers { + l.record(LevelDebug, "inspect", step+": "+strconv.Quote(identifier)) + } +} + +// LogMembership records each layer or slice and its selected files at debug level. +// Labels are sorted without mutating the supplied membership map. +func (l *Logger) LogMembership(kind string, membership map[string][]string) { + if !l.enabled(LevelDebug) { + return + } + for _, label := range slices.Sorted(maps.Keys(membership)) { + l.LogSelection(kind+" "+strconv.Quote(label), membership[label]) + } +} diff --git a/common/logging/inspection_test.go b/common/logging/inspection_test.go new file mode 100644 index 0000000..a9af834 --- /dev/null +++ b/common/logging/inspection_test.go @@ -0,0 +1,48 @@ +package logging_test + +import ( + "bytes" + "strings" + "testing" + + "github.com/LukasNiessen/ArchUnitGo/common/extraction" + "github.com/LukasNiessen/ArchUnitGo/common/logging" +) + +func TestInspectionIsDebugOnlyAndQuotesIdentifiers(t *testing.T) { + graph := extraction.NewGraph( + extraction.SelfEdge("api/handler.go"), + extraction.NewEdge("api/handler.go", "database/sql", true, extraction.ImportKindPlain), + ) + for _, level := range []logging.Level{logging.LevelDebug, logging.LevelInfo, logging.LevelWarn, logging.LevelError} { + var output bytes.Buffer + log, err := logging.NewLogger(&logging.Options{Writer: &output, Level: level}) + if err != nil { + t.Fatal(err) + } + log.LogGraph(graph) + log.LogSelection("selected file", []string{"name\nwith-newline.go"}) + log.LogMembership("layer", map[string][]string{"z": {"z.go"}, "a": {"a.go"}}) + if err := log.Close(); err != nil { + t.Fatal(err) + } + if level != logging.LevelDebug { + if output.Len() != 0 { + t.Fatalf("inspection escaped threshold %v: %s", level, &output) + } + continue + } + for _, want := range []string{`discovered file: "api/handler.go"`, `dependency: "api/handler.go" -> "database/sql"`, `external=true`, `name\nwith-newline.go`} { + if !strings.Contains(output.String(), want) { + t.Errorf("missing %q in %s", want, &output) + } + } + if strings.Index(output.String(), `layer "a"`) > strings.Index(output.String(), `layer "z"`) { + t.Fatal("membership labels must be ordered") + } + } + var disabled *logging.Logger + disabled.LogGraph(graph) + disabled.LogSelection("selected file", nil) + disabled.LogMembership("layer", nil) +} diff --git a/common/logging/logger.go b/common/logging/logger.go index c86f56d..a4c5567 100644 --- a/common/logging/logger.go +++ b/common/logging/logger.go @@ -11,7 +11,7 @@ // // Two decisions shape the whole package. The destination is injected per check rather than owned by the // library, so nothing is logged until a rule is handed a bag that says where to write; and the vocabulary -// is fixed at five records — start check, end check, log progress, log violation, log metric — so that a +// uses five lifecycle records plus debug inspection — start check, end check, log progress, log violation, log metric — so that a // log has the same five shapes of line whatever family of rule wrote it, and a reader who has learned one // has learned all of them. Level says which of them are written. // diff --git a/files/fluentapi/adhere_to.go b/files/fluentapi/adhere_to.go index 47778b0..6142019 100644 --- a/files/fluentapi/adhere_to.go +++ b/files/fluentapi/adhere_to.go @@ -126,12 +126,13 @@ func (b FilesShouldNotBuilder) AdhereTo(predicate filesassertion.FilePredicate, // violations say nothing. func (c FilesAdherenceCondition) Check(options *kernel.CheckOptions) ([]assertion.Violation, error) { return options.LoggedCheck(c, func(log *logging.Logger) ([]assertion.Violation, error) { - // The graph is deliberately dropped: this rule judges each selected file on its own contents, so the - // dependencies between them say nothing about it. - _, selected, err := c.rule.scope.resolve(options) + // Dependencies are available for debug inspection; the assertion still judges only file contents. + graph, selected, err := c.rule.scope.resolve(options) if err != nil { return nil, err } + log.LogGraph(graph) + log.LogSelection("selected file", selected) log.LogProgress("selected files", len(selected)) if empty := options.GatherEmptyTestViolations(c.rule.selection(len(selected))); len(empty) > 0 { diff --git a/files/fluentapi/depend_on_external_modules.go b/files/fluentapi/depend_on_external_modules.go index 46c229a..5867b99 100644 --- a/files/fluentapi/depend_on_external_modules.go +++ b/files/fluentapi/depend_on_external_modules.go @@ -146,6 +146,8 @@ func (c FilesExternalDependencyCondition) Check(options *kernel.CheckOptions) ([ if err != nil { return nil, err } + log.LogGraph(graph) + log.LogSelection("selected file", selected) log.LogProgress("selected files", len(selected)) if empty := options.GatherEmptyTestViolations(c.rule.selection(len(selected))); len(empty) > 0 { @@ -155,6 +157,7 @@ func (c FilesExternalDependencyCondition) Check(options *kernel.CheckOptions) ([ } modules := projection.SelectExternalModules(graph, c.modules...) + log.LogSelection("external module", modules) log.LogProgress("external modules matched", len(modules)) dependencies := kernelprojection.ProjectEdges(graph, projection.PerExternalDependencyEdge(selected, modules)) log.LogProgress("dependencies from the selected files to those modules", len(dependencies)) diff --git a/files/fluentapi/depend_on_files.go b/files/fluentapi/depend_on_files.go index 1190eb2..5e1ecae 100644 --- a/files/fluentapi/depend_on_files.go +++ b/files/fluentapi/depend_on_files.go @@ -134,7 +134,10 @@ func (c FilesDependencyCondition) Check(options *kernel.CheckOptions) ([]asserti return nil, err } objects := projection.SelectFiles(graph, c.objects...) + log.LogGraph(graph) + log.LogSelection("selected file", selected) log.LogProgress("selected files", len(selected)) + log.LogSelection("target file", objects) log.LogProgress("files to depend on", len(objects)) if empty := options.GatherEmptyTestViolations(c.populations(len(selected), len(objects))...); len(empty) > 0 { diff --git a/files/fluentapi/have_no_cycles.go b/files/fluentapi/have_no_cycles.go index 3b8682a..5615656 100644 --- a/files/fluentapi/have_no_cycles.go +++ b/files/fluentapi/have_no_cycles.go @@ -71,6 +71,8 @@ func (c FilesCyclesCondition) Check(options *kernel.CheckOptions) ([]assertion.V if err != nil { return nil, err } + log.LogGraph(graph) + log.LogSelection("selected file", selected) log.LogProgress("selected files", len(selected)) if empty := options.GatherEmptyTestViolations(c.rule.selection(len(selected))); len(empty) > 0 { diff --git a/files/fluentapi/logged_progress_test.go b/files/fluentapi/logged_progress_test.go index 3d928e2..8817765 100644 --- a/files/fluentapi/logged_progress_test.go +++ b/files/fluentapi/logged_progress_test.go @@ -2,6 +2,7 @@ package fluentapi_test import ( "bytes" + "reflect" "slices" "strings" "testing" @@ -126,3 +127,31 @@ func loggedRecords(t *testing.T, rule kernel.Checkable, prefix string) []string } return records } + +func TestDebugInspectionExplainsSelectionWithoutChangingResults(t *testing.T) { + fixture := fixtureLocator(t, writeFixtureProject(t)) + rule := fluentapi.ProjectFiles(fixture).InFolder("internal/api/**").Should().HaveName("*_missing.go") + baseline, err := rule.Check(nil) + if err != nil { + t.Fatal(err) + } + for _, level := range []logging.Level{logging.LevelDebug, logging.LevelInfo} { + var output bytes.Buffer + actual, err := rule.Check(&kernel.CheckOptions{Logging: &logging.Options{Writer: &output, Level: level}}) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(actual, baseline) { + t.Fatalf("logging changed violations: %v", actual) + } + if level == logging.LevelDebug { + for _, want := range []string{"inspect: discovered file:", "inspect: dependency:", "inspect: selected file:"} { + if !strings.Contains(output.String(), want) { + t.Errorf("missing %q in %s", want, &output) + } + } + } else if strings.Contains(output.String(), "inspect:") { + t.Fatal("info must omit inspection") + } + } +} diff --git a/files/fluentapi/naming_condition.go b/files/fluentapi/naming_condition.go index 82e023a..00045b1 100644 --- a/files/fluentapi/naming_condition.go +++ b/files/fluentapi/naming_condition.go @@ -64,12 +64,12 @@ type FilesNamingCondition struct { // opened, written or closed — and never a failing rule. When it is non-nil the violations say nothing. func (c FilesNamingCondition) Check(options *kernel.CheckOptions) ([]assertion.Violation, error) { return options.LoggedCheck(c, func(log *logging.Logger) ([]assertion.Violation, error) { - // The graph is deliberately dropped: what a file is called and where it lives is on the file, so this - // rule is about the selection and not about the dependencies between the files in it. - _, selected, err := c.rule.scope.resolve(options) + graph, selected, err := c.rule.scope.resolve(options) if err != nil { return nil, err } + log.LogGraph(graph) + log.LogSelection("selected file", selected) log.LogProgress("selected files", len(selected)) if empty := options.GatherEmptyTestViolations(c.rule.selection(len(selected))); len(empty) > 0 { diff --git a/layers/fluentapi/policy_condition.go b/layers/fluentapi/policy_condition.go index 69c415c..73297f2 100644 --- a/layers/fluentapi/policy_condition.go +++ b/layers/fluentapi/policy_condition.go @@ -63,6 +63,8 @@ func (c LayersPolicyCondition) Check(options *kernel.CheckOptions) ([]assertion. if err != nil { return nil, err } + log.LogGraph(graph) + log.LogMembership("layer", membership) log.LogProgress("declared layers", len(c.policy.declaredLayers())) log.LogProgress("clauses", len(c.policy.clauses)) diff --git a/metrics/fluentapi/metrics.go b/metrics/fluentapi/metrics.go index 101f63b..38e4b05 100644 --- a/metrics/fluentapi/metrics.go +++ b/metrics/fluentapi/metrics.go @@ -58,6 +58,7 @@ import ( "github.com/LukasNiessen/ArchUnitGo/common/archerror" "github.com/LukasNiessen/ArchUnitGo/common/extraction" kernel "github.com/LukasNiessen/ArchUnitGo/common/fluentapi" + "github.com/LukasNiessen/ArchUnitGo/common/logging" "github.com/LukasNiessen/ArchUnitGo/common/matching" metricsextraction "github.com/LukasNiessen/ArchUnitGo/metrics/extraction" "github.com/LukasNiessen/ArchUnitGo/metrics/projection" @@ -188,6 +189,11 @@ func (b MetricsBuilder) String() string { // A pattern a scope verb rejected is returned before the project is read, and the error is otherwise a // project that cannot be located, extracted or read. It is never a rule failure. func (b MetricsBuilder) resolve(options *kernel.CheckOptions) (projection.Subjects, error) { + return b.resolveLogged(options, nil) +} + +// resolveLogged shares the existing extraction and observes it only when debug is enabled. +func (b MetricsBuilder) resolveLogged(options *kernel.CheckOptions, log *logging.Logger) (projection.Subjects, error) { if b.err != nil { return projection.Subjects{}, b.err } @@ -195,11 +201,14 @@ func (b MetricsBuilder) resolve(options *kernel.CheckOptions) (projection.Subjec if err != nil { return projection.Subjects{}, err } + log.LogGraph(graph) + selected := projection.SelectFiles(graph, b.fileSelectors()...) + log.LogSelection("metric file", selected) root, err := extraction.LocateProject(b.locator) if err != nil { return projection.Subjects{}, err } - files, err := metricsextraction.ExtractFileInfo(root, projection.SelectFiles(graph, b.fileSelectors()...)) + files, err := metricsextraction.ExtractFileInfo(root, selected) if err != nil { return projection.Subjects{}, err } diff --git a/metrics/fluentapi/should_be.go b/metrics/fluentapi/should_be.go index d46bd8f..568f546 100644 --- a/metrics/fluentapi/should_be.go +++ b/metrics/fluentapi/should_be.go @@ -158,7 +158,7 @@ func (b MetricBuilder) ShouldBeAboveOrEqual(limit float64) MetricsThresholdCondi // opened, written or closed — and never a failing rule. When it is non-nil the violations say nothing. func (c MetricsThresholdCondition) Check(options *kernel.CheckOptions) ([]assertion.Violation, error) { return options.LoggedCheck(c, func(log *logging.Logger) ([]assertion.Violation, error) { - subjects, err := c.rule.scope.resolve(options) + subjects, err := c.rule.scope.resolveLogged(options, log) if err != nil { return nil, err } diff --git a/metrics/fluentapi/should_satisfy.go b/metrics/fluentapi/should_satisfy.go index 328110a..9f3e003 100644 --- a/metrics/fluentapi/should_satisfy.go +++ b/metrics/fluentapi/should_satisfy.go @@ -137,7 +137,7 @@ func (b MetricBuilder) ShouldSatisfy(predicate metricsassertion.Satisfaction, re // nothing. func (c MetricsSatisfactionCondition) Check(options *kernel.CheckOptions) ([]assertion.Violation, error) { return options.LoggedCheck(c, func(log *logging.Logger) ([]assertion.Violation, error) { - subjects, err := c.rule.scope.resolve(options) + subjects, err := c.rule.scope.resolveLogged(options, log) if err != nil { return nil, err } diff --git a/metrics/fluentapi/zone_checks.go b/metrics/fluentapi/zone_checks.go index 207eff3..3665a0f 100644 --- a/metrics/fluentapi/zone_checks.go +++ b/metrics/fluentapi/zone_checks.go @@ -91,7 +91,7 @@ func (b MetricsDistanceBuilder) ShouldNotBeInZoneOfUselessness() MetricsZoneCond // closed — and never a failing rule. When it is non-nil the violations say nothing. func (c MetricsZoneCondition) Check(options *kernel.CheckOptions) ([]assertion.Violation, error) { return options.LoggedCheck(c, func(log *logging.Logger) ([]assertion.Violation, error) { - subjects, err := c.scope.resolve(options) + subjects, err := c.scope.resolveLogged(options, log) if err != nil { return nil, err } diff --git a/slices/fluentapi/adhere_to_diagram.go b/slices/fluentapi/adhere_to_diagram.go index 011a135..a351d97 100644 --- a/slices/fluentapi/adhere_to_diagram.go +++ b/slices/fluentapi/adhere_to_diagram.go @@ -211,6 +211,8 @@ func (c SlicesDiagramCondition) Check(options *kernel.CheckOptions) ([]assertion if err != nil { return nil, err } + log.LogGraph(graph) + log.LogMembership("slice", membership) log.LogProgress("slices the slicing found", len(membership)) diagram, err := c.drawing() diff --git a/slices/fluentapi/contain_dependency.go b/slices/fluentapi/contain_dependency.go index 5ce2ef2..62981e2 100644 --- a/slices/fluentapi/contain_dependency.go +++ b/slices/fluentapi/contain_dependency.go @@ -98,6 +98,8 @@ func (c SlicesDependencyCondition) Check(options *kernel.CheckOptions) ([]assert if err != nil { return nil, err } + log.LogGraph(graph) + log.LogMembership("slice", membership) log.LogProgress("slices the slicing found", len(membership)) if empty := options.GatherEmptyTestViolations(c.populations(membership)...); len(empty) > 0 { From 3a4e9761f2235d0c799287dae7d5d3dcb9aac52e Mon Sep 17 00:00:00 2001 From: Lukas Niessen Date: Wed, 30 Sep 2026 18:11:18 +0200 Subject: [PATCH 2/3] Clarify inspection records and release guidance --- README.md | 2 +- common/logging/logger.go | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 994c9eb..f912a29 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,7 @@ go get github.com/LukasNiessen/ArchUnitGo ``` Go 1.26 or newer. The only direct dependency is `golang.org/x/tools`, which is how the extractor talks -to the Go toolchain. The latest release is v0.0.1; it is pre-1.0, so the API may still move. +to the Go toolchain. Releases are pre-1.0, so the API may still move. The package is `archunit` while the last element of the module path is `ArchUnitGo`, so give the import the name it has: diff --git a/common/logging/logger.go b/common/logging/logger.go index a4c5567..f657fc2 100644 --- a/common/logging/logger.go +++ b/common/logging/logger.go @@ -11,9 +11,9 @@ // // Two decisions shape the whole package. The destination is injected per check rather than owned by the // library, so nothing is logged until a rule is handed a bag that says where to write; and the vocabulary -// uses five lifecycle records plus debug inspection — start check, end check, log progress, log violation, log metric — so that a -// log has the same five shapes of line whatever family of rule wrote it, and a reader who has learned one -// has learned all of them. Level says which of them are written. +// uses five lifecycle records — start check, end check, log progress, log violation, log metric — plus +// debug inspection of graphs and selections. Every family uses the same aligned format, and Level says +// which records are written. // // Nothing here is a channel for reporting a failure. A technical failure is the error Check returns and a // broken rule is a violation in the list it returns; both are logged as well, because a log of a run is From 0d1b752f12db055e683375be7ffc171d62c4f7f0 Mon Sep 17 00:00:00 2001 From: Lukas Niessen Date: Wed, 30 Sep 2026 18:21:41 +0200 Subject: [PATCH 3/3] Verify lifecycle output alongside detailed inspection records --- archunit_test.go | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/archunit_test.go b/archunit_test.go index 3fd6bb8..b9f9e8f 100644 --- a/archunit_test.go +++ b/archunit_test.go @@ -3322,8 +3322,7 @@ func TestARuleOfThisRepositoryLogsWhatItDidThroughThePublicSurface(t *testing.T) if len(violations) != 2 { t.Fatalf("%s reported %v, want the two empty populations", rule, violations) } - // The five records of the fixed vocabulary, in the order a check writes them: the rule, the steps it took - // and how much of the project each came to, what it found, and what came of it. + // The lifecycle records retain their order and shape alongside graph inspection. want := strings.Join([]string{ "info start check: " + rule.String(), "debug progress: selected files: 0", @@ -3333,8 +3332,15 @@ func TestARuleOfThisRepositoryLogsWhatItDidThroughThePublicSurface(t *testing.T) "info end check: " + rule.String() + ": 2 violations", "", }, "\n") - if log.String() != want { - t.Errorf("the log holds\n%s\nwant\n%s", log.String(), want) + records := strings.Split(log.String(), "\n") + lifecycle := slices.DeleteFunc(records, func(record string) bool { + return strings.HasPrefix(record, "debug inspect:") + }) + if actual := strings.Join(lifecycle, "\n"); actual != want { + t.Errorf("the lifecycle log holds\n%s\nwant\n%s", actual, want) + } + if !strings.Contains(log.String(), `debug inspect: discovered file: "common/logging/inspection.go"`) { + t.Error("debug logging must expose discovered files even when the selectors match nothing") } }