The .NET realization of the logging principles (see the `logging` skill for the why) — Serilog is the accepted coupling. Use when writing or reviewing ANY log statement in .NET (ILogger calls, LogInformation/Warning/Error), pushing properties into the log context, adding logging to handlers, services, consumers or jobs, or configuring Serilog. It encodes: the message as GetType().Name, LogContext.PushProperty for single statements and one PushProperties helper per class when the same set serv...
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Logging Dotnet?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/jorgecostamacia-logging-dotnet-code-harness)
---
name: logging-dotnet
description: >-
The .NET realization of the logging principles (see the `logging` skill for
the why) — Serilog is the accepted coupling. Use when writing or reviewing
ANY log statement in .NET (ILogger calls, LogInformation/Warning/Error),
pushing properties into the log context, adding logging to handlers,
services, consumers or jobs, or configuring Serilog. It encodes: the
message as GetType().Name, LogContext.PushProperty for single statements
and one PushProperties helper per class when the same set serves several,
destructureObjects for payloads, secret fields marked for masking
([NotLogged] or a destructuring transform), the exception as LogError's
first argument, correlation properties in every scope, the
JorgeCostaMacia.Serilog pipeline packages, a 500 with only its status,
trace id and request id, and minimum levels set in configuration.
---
# Logging in .NET (Serilog)
The .NET *how* of `logging` (load it for the *why*). **Serilog is the accepted core coupling** — not wrapped, not replaced. Code logs through an injected `ILogger<T>`; Serilog is the provider behind it.
**The libraries:** the baseline (`JorgeCostaMacia.Serilog`) lives in [serilog-dotnet](https://github.com/JorgeCostaMacia/serilog-dotnet), and the HTTP request and exception logging (`JorgeCostaMacia.Http.Serilog`, `JorgeCostaMacia.Http.Exception.Serilog`) in [http-dotnet](https://github.com/JorgeCostaMacia/http-dotnet). How they work inside is their READMEs'; this skill is how the code logs.
## The message
```csharp
_logger.LogInformation(GetType().Name);
```
The class's own name is the grouping key: fixed, unique, and never typed by hand. Use a literal (`"UserLoad"`) only where one class logs more than one event. The literal is the event's name in PascalCase, with no spaces and no full stop (`"ProducerFailed"`, `"RequestEnd"`). So every message, a class name or a literal, has one shape in the log store. If a library wraps a framework whose events already have names, it keeps those names (`JobToBeExecuted`, Quartz's own callbacks).
- No interpolation (`$"…"`), no `{Placeholder}` templates. Serilog keeps the template and its properties apart, but the store groups on the rendered line. The value of a placeholder lands in that line (see `logging`).
- Failure: `_logger.LogError(exception, GetType().Name)` — **the exception is the first argument**, so Serilog captures it structured. The message is the same as on the success path; the level tells them apart.
- Levels keep `logging`'s names through `ILogger` (`Information`, `Warning`, `Error`, `Critical`). Serilog writes `Critical` as `Fatal`. It is the same level, so a `MinimumLevel` of `Fatal` in configuration is `Critical` in code.
## Properties — through the log context
Push every property into `Serilog.Context.LogContext` around the statement. The line carries every property that the context holds when Serilog writes the line.
**One log statement — push each property in its own `using`:**
```csharp
using (LogContext.PushProperty("PageSize", context.Message.PageSize))
using (LogContext.PushProperty("Commands", commands.Count))
using (LogContext.PushProperty("AggregateId", context.Message.AggregateId))
using (LogContext.PushProperty("CorrelationId", context.Message.AggregateCorrelationId))
{
_logger.LogInformation(GetType().Name);
}
```
It reads at a glance, and a generated handler stays uniform with every other.
**The same set in several statements — one `PushProperties` helper per class**, so the list lives once and the statements cannot drift apart. Today only the libraries' own loggers log several lines with one set, and the bus's logger does it this way. An application class logs one line:
```csharp
private static IDisposable PushProperties(
UserLoadRequest request,
Guid correlationId)
=> LogContext.Push(
new PropertyEnricher("AggregateId", request.AggregateId),
new PropertyEnricher("CorrelationId", correlationId),
new PropertyEnricher("UserId", request.UserId),
new PropertyEnricher("Request", request, destructureObjects: true));
```
```csharp
using (PushProperties(request, correlationId))
{
_logger.LogInformation(GetType().Name);
}
```
- `PropertyEnricher` lives in `Serilog.Core.Enrichers`; `LogContext.Push` takes them all and returns one disposable.
- **`destructureObjects: true`** for a complex payload — logged as a structured object, not its `ToString()`.
- **Mark every secret field so that the log masks it.** This is the rule, not an option: a secret never reaches a line, in any store (see `logging`). A secret field of a request or a message (a password, a token, an API key, a connection string) carries `[NotLogged]` or `[LogMasked]` from `Destructurama.Attributed`, and the host's logger configuration adds `.Destructure.UsingAttributes()`. For a type that you cannot mark, the host registers a destructuring transform (`.Destructure.ByTransforming<T>(…)`) that leaves the secret out. Without one of the two, `destructureObjects: true` logs every field. A project without a private log store marks the personal fields the same way.
- **`AggregateId` and `CorrelationId` in every scope**, under those names, so every service's lines join on them.
- If another library in the project ships its own `LogContext`, alias Serilog's: `using LogContext = Serilog.Context.LogContext;`.
## Wiring — the host
Every host registers Serilog the same way, in its `ProgramBuilder`:
```csharp
if (builder.Environment.IsDevelopment())
{
Serilog.Debugging.SelfLog.Enable(Console.Error); // Serilog's own errors (a broken sink, a bad config)
}
builder.Services.AddSerilog((services, config) => config
.ReadFrom.Configuration(builder.Configuration) // levels, overrides and sinks from appsettings
.WithDefaults()); // JorgeCostaMacia.Serilog
```
`WithDefaults()` (`JorgeCostaMacia.Serilog.Infrastructure`) adds what every line needs: `FromLogContext`, the thread and process ids, structured exception details, and the entry assembly's `Version` and `Application`. Without `FromLogContext`, no pushed property reaches the line. Don't re-add those enrichers by hand; anything a service needs on top is configuration.
### HTTP hosts
The request and exception logging come from `JorgeCostaMacia.Http.Serilog` and `JorgeCostaMacia.Http.Exception.Serilog`:
```csharp
// ProgramBuilder
builder.Services.AddExceptionHandler<ExceptionHandler>(); // logs the exception once, maps it to ProblemDetails
// ProgramApplication — order matters
app.UseForwardedHeaders(new ForwardedHeadersOptions().WithDefaults()); // only behind a proxy that terminates TLS
app.UseBodyBufferMiddleware(); // lets the request body be read for the log
app.UseEnrichRequestMiddleware(); // pushes the request's properties around the rest
app.UseSerilogRequestLogging(options => options.WithDefaults());
app.UseExceptionHandler(new ExceptionHandlerOptions().WithDefaultStatusCodes());
app.UseStatusCodePages();
app.UseRouting();
app.UseAuthentication();
app.UseEnrichAuthenticationMiddleware(); // pushes the authenticated user
app.UseAuthorization();
```
**The request log wraps the exception handler and authorization**. Then it logs a failed request with the status it really got (400, 500), and it logs a refused one (401, 403) too. If the request log is inside the exception handler, it logs every failure as a 500. An endpoint handler logs nothing of its own: the request log is its line, with the status it answered and the properties the enrichers pushed.
- **Forwarded headers come first** when the host is behind a proxy that terminates TLS (`JorgeCostaMacia.Http.ForwardedHeaders`). Then the request log records the client's address and scheme, not the proxy's.
- **The request body goes only to a private log store**, like every payload (see `logging`). The HTTP logging library is expected to mask the `Authorization`, `Cookie` and `Set-Cookie` headers and every field marked for masking by default. A secret never reaches a line, in any store.
- **A 500 returns only its status, trace id and request id.** The rule is in `clean-architecture-dotnet`, where the endpoint is composed. The exception goes to the log.
- This sample is the logging part of the pipeline. What the API's exposure adds (authentication by default, CORS, HSTS, a rate limiter) is in `clean-architecture-dotnet`.
### Bus hosts
The bus pipeline logs a failed message, its retry and its parking. The payload is required on those lines, and recommended on the success line (see `logging`). It goes only to a private log store, and its secret fields are marked so that the log masks them (see *Properties* above). The bus transports push the message `Body` into the log context of the whole delivery, so every line of a delivery carries it: the pipeline's lines, and the handler's own success line too. A handler therefore never logs the payload itself. It logs only its own success line, with its parameters and counts. It lets an exception propagate: a second log of the exception in the handler would log one failure twice.
## Configuration
Serilog reads its configuration from `appsettings` (`Serilog:MinimumLevel`). To turn a source up or down, use **`MinimumLevel:Override`**; never delete statements. A `Default` of `Error` can hide the expected-failure `Warning`s of a library. If the default is stricter than a package's own logs, override that package's namespace instead of lowering the default.