Roslyn analyzer results on the command line with SARIF
By terje
dotnet build does not show you everything the Roslyn analyzers find. It prints errors and warnings, but most analyzer rules report at info level, which Visual Studio calls “Messages”. Those show up in the Error List in Visual Studio and nowhere on the command line.
This post shows how to get all of them on the command line, using a SARIF log.
The problem
I upgraded a solution to NUnit 5.0.0. After fixing some compile errors, the build was clean:
dotnet build MyProject.Tests
0 Warning(s)
0 Error(s)
No NUnit.Analyzers warnings, so all good? No. The same projects had 123 NUnit.Analyzers findings, all at info level: asserts that should be grouped in a multiple-assert scope (NUnit2045), .Count comparisons that should use Has.Count (NUnit2046), and so on. The console never showed them.
That matters when you work from the command line, in CI, or with an AI agent that only sees console output. What the build prints is all they know.
What SARIF is
SARIF, the Static Analysis Results Interchange Format, is a standard JSON format for static-analysis results. It is an OASIS standard, and GitHub code scanning and many other tools read it.
The C# compiler can write every diagnostic it reports into a SARIF file, info level included. You turn it on with the ErrorLog MSBuild property.
The command
dotnet build MyProject.Tests --no-incremental "-p:ErrorLog=c:/temp/tests.sarif%2Cversion=2.1"
Three things to watch:
%2Cis an escaped comma. The value isfile,version=2.1, but a plain comma would split the property.version=2.1asks for SARIF 2.1 instead of the older 1.0 format.- Use
--no-incremental. If the project is up to date, the compiler does not run, the analyzers do not run, and you get a stale file or no file at all. - Build one project per SARIF file.
ErrorLogis a global property, so it flows to all referenced projects, and they all write to the same path. The project you named builds last, so the file ends up with its results, but don’t build a whole solution into one file and expect all of it there.
Reading the result
The file is large: a few hundred KB for a test project, mostly rule descriptions. The interesting part is runs[].results[], with one entry per diagnostic:
{
"ruleId": "CA1861",
"level": "note",
"message": {
"text": "Prefer 'static readonly' fields over constant array arguments if the called method is called repeatedly and is not mutating the passed array"
},
"locations": [ {
"physicalLocation": {
"artifactLocation": { "uri": "file:///c:/src/MyProject.Tests/CorsOriginsTests.cs" },
"region": { "startLine": 12, "startColumn": 40, "endLine": 17, "endColumn": 10 }
}
} ]
}
SARIF levels are error, warning and note. note is what Visual Studio calls info or “Message”.
Each rule is described once under runs[].tool.driver.rules[], with its description, default level, category and a helpUri to the documentation:
{
"id": "NUnit2045",
"shortDescription": { "text": "Use Assert.EnterMultipleScope or Assert.Multiple" },
"defaultConfiguration": { "level": "note" },
"helpUri": "https://github.com/nunit/nunit.analyzers/tree/master/documentation/NUnit2045.md",
"properties": { "category": "Assertion" }
}
A short Python script gives a count per rule:
import collections
import json
import sys
for path in sys.argv[1:]:
with open(path, encoding="utf-8-sig") as f:
log = json.load(f)
counts = collections.Counter(
(r.get("level", "warning"), r["ruleId"])
for run in log["runs"]
for r in run.get("results", []))
print("==", path)
for (level, rule), n in sorted(counts.items(), key=lambda x: x[0][1]):
print(f"{n:5} {level:8} {rule}")
python sarif_summary.py c:/temp/tests.sarif
== c:/temp/tests.sarif
5 note CA1822
12 note CA1861
108 note NUnit2045
2 note NUnit2046
3 note NUnit4002
Now you see what Visual Studio sees.
Fixing them from the command line too
Many analyzers ship code fixes, and dotnet format can run them without opening Visual Studio:
dotnet format analyzers MyProject.Tests/MyProject.Tests.csproj --diagnostics NUnit2045 NUnit2046 NUnit4002 NUnit2056 --severity info
--severity info is needed, because the default only fixes warnings and errors. Run the SARIF build again afterwards. Some fixes produce code that triggers the same rule again, and a second pass may be needed. Also read the diff: the code fix for NUnit2045 sometimes leaves two multiple-assert scopes right next to each other, which you want to merge by hand.
Alternative: raise the severity
If you want these findings in the normal build output, and in CI, you can raise their severity in .editorconfig, one rule at a time:
[*.cs]
dotnet_diagnostic.NUnit2045.severity = warning
dotnet_diagnostic.NUnit2046.severity = warning
Note that there is no “NUnit” category to raise in one go. NUnit.Analyzers uses categories like Assertion and Structure, as the category property in the SARIF rules shows.
Either way, it is a decision for the repo. SARIF works without changing anything.
Summary
- Info-level analyzer findings never show in
dotnet buildoutput. -p:ErrorLog=file.sarif%2Cversion=2.1together with--no-incrementalwrites all of them to a SARIF file.- Use one SARIF file per project.
dotnet format analyzers --severity infoapplies the code fixes.