All jobs

Add Structured Logging to a .NET App

Yes. An agent adds Serilog to your .NET 10 solution: JSON console lines, one event per request, config in appsettings.json, OpenTelemetry kept, and a PR.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

The agent reads the host before it changes how it logs. In a solution laid out like jasontaylordev/CleanArchitecture, global.json pins SDK 10.0.403, Directory.Build.props sets net10.0, TreatWarningsAsErrors and an ArtifactsPath, and Directory.Packages.props manages every version centrally (ManagePackageVersionsCentrally with transitive pinning): OpenTelemetry 1.20.1, Aspire 13.6.4, MediatR 14.2.0, NUnit 5, and no Serilog. src/Web/Program.cs calls builder.AddServiceDefaults() and then the three Add...Services extensions, maps OpenAPI and Scalar, UseExceptionHandler, MapDefaultEndpoints and MapEndpoints. src/ServiceDefaults/Extensions.cs is where logging is configured today: builder.Logging.AddOpenTelemetry with IncludeFormattedMessage and IncludeScopes, and an OTLP exporter when OTEL_EXPORTER_OTLP_ENDPOINT is set. appsettings.json has a Logging:LogLevel block (Default Information, Microsoft Warning), and appsettings.PostgreSQL.json, SQLite.json and SQLServer.json repeat it, with <!--#if--> template markers in the project files because the repository is also a dotnet new template. The MediatR behaviours in src/Application/Common/Behaviours already write Serilog-style templates: LoggingBehaviour logs "CleanArchitecture Request: {Name} {@UserId} {@UserName} {@Request}", PerformanceBehaviour warns past 500 ms with the same shape, UnhandledExceptionBehaviour logs the exception with {@Request}. The @ destructuring is meaningless to the default console provider, which prints ToString().

It adds Serilog.AspNetCore (10.0.0 on NuGet when this page was written) as a PackageVersion in Directory.Packages.props and a PackageReference in Web.csproj; the package carries the compact JSON formatter and the configuration reader. Program.cs takes the two-stage shape from the Serilog README: Log.Logger = new LoggerConfiguration().WriteTo.Console().CreateBootstrapLogger() before the builder, a try around the host with Log.Fatal in catch and Log.CloseAndFlush() in finally, and builder.Services.AddSerilog((services, lc) => lc.ReadFrom.Configuration(builder.Configuration).ReadFrom.Services(services).Enrich.FromLogContext().WriteTo.Console(new RenderedCompactJsonFormatter()), writeToProviders: true). The last argument matters here: by default Serilog does not forward events to ILoggerProviders registered through Microsoft logging, and AddServiceDefaults registers exactly one, the OpenTelemetry provider that ships logs to the Aspire dashboard and the OTLP endpoint. With writeToProviders true, the console gets JSON and the exporter keeps receiving events.

app.UseSerilogRequestLogging() goes before MapEndpoints, so one event per request carries RequestMethod, RequestPath, StatusCode and Elapsed in place of the several hosting events, with EnrichDiagnosticContext adding the request host and the user id from IUser when there is one. The Logging sections become Serilog sections, with MinimumLevel.Override for Microsoft.AspNetCore.Hosting, Mvc and Routing at Warning as the README asks when request logging is on, and Microsoft.EntityFrameworkCore at Warning so queries do not drown the stream. Because {@Request} now destructures the whole command, the agent adds Destructure.ToMaximumDepth(3) and ToMaximumStringLength(1024) so a command carrying a long body stays one readable line, and notes in the pull request which commands carry fields a reviewer may want masked.

It builds with dotnet build --configuration Release, where warnings are errors, runs dotnet test, then starts src/Web and calls /api/TodoLists to show one JSON line per request with the four request properties and a LoggingBehaviour event whose Request is an object rather than a type name. The #if markers in the project and settings files are kept intact so the repository still packs as a template.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "Add structured logging with Serilog to this .NET 10 Clean Architecture solution. Read global.json, Directory.Build.props, Directory.Packages.props, src/Web/Program.cs, src/Web/Web.csproj, src/ServiceDefaults/Extensions.cs, every appsettings*.json under src/Web, the behaviours under src/Application/Common/Behaviours and the workflows under .github first. Add Serilog.AspNetCore through central package management. In Program.cs create a bootstrap logger, wrap the host in try/catch/finally with Log.Fatal and Log.CloseAndFlush, and call builder.Services.AddSerilog with ReadFrom.Configuration, ReadFrom.Services, Enrich.FromLogContext and a RenderedCompactJsonFormatter console sink, passing writeToProviders true so the OpenTelemetry logging provider from AddServiceDefaults keeps receiving events. Add app.UseSerilogRequestLogging before MapEndpoints with the host and user id in the diagnostic context. Replace every Logging section with a Serilog section that overrides Microsoft.AspNetCore.Hosting, Mvc, Routing and Microsoft.EntityFrameworkCore to Warning. Add destructuring depth and string length limits. Keep the #if template markers. Run dotnet build --configuration Release and dotnet test, start the Web project and show one JSON log line for a request, then open a pull request that quotes that line and the test output.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
  1. Get an API key. In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
  2. Send the request. POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
  3. Read what came back. Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

What comes back

The pull request changes Directory.Packages.props, src/Web/Web.csproj, src/Web/Program.cs and the four appsettings*.json files under src/Web. Its description quotes one request line and one LoggingBehaviour line as the console now prints them, shows the dotnet test summary, and states that the OpenTelemetry provider is still wired so the Aspire dashboard and any OTLP collector see the same events.

A reviewer reads Program.cs for the two-stage setup and the writeToProviders argument, since forgetting it silently cuts the dashboard off, then reads the Serilog section in appsettings.json to decide the production minimum levels. They run the app with ASPNETCORE_ENVIRONMENT=Development and confirm the request line and the behaviour lines are single JSON objects. The open question is masking: which command fields should never appear in {@Request}, which is a policy the team sets in the pipeline once it has seen the output.

The functional tests, which host the app through Aspire.Hosting.Testing, keep passing because logging providers are additive and nothing in them asserts on log output.

Run it on every .NET service joining the platform

A platform team sends this body once per repository from its own server, each POST /o/{org}/sessions naming that repository in resources with a request_id that is a UUID v5 of the repository name, so a retried call returns the run already started. Each run reads its own Program.cs; a service without Aspire's service defaults gets the same Serilog setup without the writeToProviders note, and one with a Logging section in a different file gets that file changed.

An automation on the Project with a github trigger on pull_request.opened and the prompt "if this pull request adds a log call with string concatenation or a template without named properties, post a review citing the line and the structured form" keeps new code on the same footing. The trigger adds the pull request after the prompt and fills in nothing else.

The use case this job follows, with its automation and trigger: Hand off a long task.

Why run it on Rush?

The risky part of this change is invisible in a diff: whether the exporter that feeds the dashboard still gets events after Serilog takes over, and whether warnings-as-errors accepts the new code. The agent builds in Release in its own sandbox, runs the suite, starts the service and reads a real request line before it opens the pull request, and every command stays attached to the run.

A reviewer reads one Program.cs and one settings section with the output already in front of them. A team with a dozen services starts the same request across all of them at once and gets a pull request per service that matches that service's host setup.

Frequently asked questions

Does this replace the OpenTelemetry logging?

No. AddServiceDefaults registers the OpenTelemetry logging provider, and Serilog by default does not write to providers registered that way. The agent passes writeToProviders: true so the console gets JSON from Serilog while the exporter keeps receiving the same events.

Why JSON on the console rather than a file?

The solution deploys to Azure Container Apps through its AppHost, where the console is what the platform collects. RenderedCompactJsonFormatter writes one object per line with the message rendered, which log pipelines parse without configuration; a file sink can be added in the Serilog section without code changes.

Will {@Request} log sensitive fields?

It destructures the whole MediatR command, which is what the existing behaviours already ask for. The agent caps depth and string length and lists the command types it found, so the team can add a destructuring policy or exclude properties before this reaches production.

Does it change the template markers?

No. The <!--#if--> and #if lines that make this repository a dotnet new template are left in place, and the new code sits outside them so every template variant gets Serilog.

What about the tests?

They build under warnings-as-errors and run with dotnet test; the functional tests host the Web project through Aspire's testing package and are unaffected by an extra logging provider. The pull request quotes the summary.

More .NET jobs

The same job on other stacks

Keep reading