logging
Skill853 starsChanged yesterdayMITView on GitHub
Logging for .NET 10: ILogger message templates, [LoggerMessage] source generation, Serilog (references/serilog.md), health check endpoints, correlation IDs, log levels. Use for "ILogger", "Serilog", "structured logging", "LoggerMessage", "Seq", "correlation ID", "health checks". Do NOT use for traces, metrics or OTLP SDK setup (use opentelemetry) or retry and circuit-breaker policies (use resilience).
28 other projects use a version of this, 1 of them edited.
Adopted by
Most recently taken up by
- anmolnagpal/devops-skillstheir own version, first seen Nov 29, 2026
- lawless-m/claude-skillstheir own version, first seen Nov 28, 2026
- travissmithv1/claude-skillstheir own version, first seen Nov 16, 2026
- zdanovichnick/dotnet-pilottheir own version, first seen Nov 8, 2026
- codewithmukesh/dotnet-claude-kitword for word, first seen Nov 8, 2026
- gabrielbauman/skillstheir own version, first seen Nov 1, 2026
Used with
Projects with it also use api-versioning, vertical-slice and 2 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
wpankSkillapi-versioning
API versioning strategies — URL path, header, query param, content negotiation — with breaking change classification, deprecation timelines, migration patterns, and multi-version support. Use when evolving APIs, planning breaking changes, or managing version lifecycles.
Also in 3 projects that use this
hongyuancSkillvertical-slice
Build and evaluate a production-quality vertical slice before advancing from Pre-Production to Production.
Also in 3 projects that use this
lukevellaSkillbetter-auth-security-best-practices
This skill provides guidance for implementing security features that span across Better Auth, including rate limiting, CSRF protection, session security, trusted origins, secret management, OAuth security, IP tracking, and security auditing. These topics are not covered in individual plugin skills.
Also in 3 projects that use this
dbtlrSkilldependencies
Use when adding, evaluating, or updating Rust crate dependencies. Also use when considering whether to implement something yourself vs pulling in a library.
Also in 3 projects that use this
Other versions28 projects use a version of this.
Word for word · 1
- codewithmukesh/dotnet-claude-kit★ 853100% same
Edited · 1
- Resgrid/Core★ 23917% same
Wrote their own version · 26
- elie222/inbox-zero★ 13ksame name
- lukevella/rallly★ 5.4ksame name
- epicenter-md/epicenter★ 4.8ksame name
- EpicenterHQ/epicenter★ 4.8ksame name
- golemcloud/golem★ 1.5ksame name
- emavgl/oinkoin★ 486same name
- QuantConnect/Documentation★ 268same name
- anmolnagpal/devops-skills★ 9same name
- lawless-m/claude-skills★ 6same name
- zdanovichnick/dotnet-pilot★ 5same name
16 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository38 other files it gives its agents.
- AGENTS.mdAGENTS.md
- .codex/AGENTS.mdAGENTS.md
- .opencode/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- .cursor/rules/dotnet-rules.mdCursor rule
- architecture-advisorSkill
- aspireSkill
- authenticationSkill
- build-fixSkill
- cachingSkill
- ci-cdSkill
- code-reviewSkill
- configurationSkill
- console-cliSkill
- dependency-injectionSkill
- desktop-mvvmSkill
- de-sloppifySkill
- dockerSkill
- doctorSkill
- dotnet-initSkill
- ef-coreSkill
- error-handlingSkill
- instinct-systemSkill
- messagingSkill
- migrateSkill
- minimal-apiSkill
- modern-csharpSkill
- modular-slicesSkill
- native-aotSkill
- openapiSkill
- opentelemetrySkill
- resilienceSkill
- scaffoldSkill
- specSkill
- tddSkill
- testingSkill
- verifySkill
- wrap-upSkill
The file
Files
Logging & Observability
Core Principles
ILogger<T>is the API, Serilog is the provider — Application code depends only onMicrosoft.Extensions.Logging. Serilog plugs in underneath for sinks, enrichment, and configuration. Swapping the provider never touches call sites.- Structured events, never formatted strings —
{OrderId}in a message template creates a queryable property. String interpolation destroys that structure and allocates even when the level is off. [LoggerMessage]on hot paths and shared messages — The source generator emits the delegate at compile time: no boxing, no template parsing, zero allocations when the level is disabled.- Health checks answer two questions — Liveness ("restart me?") and readiness ("send traffic?") are separate endpoints. Conflating them turns a slow database into a restart loop.
- One correlation ID per request — Push it once at the pipeline edge so every log line, and every outgoing call, carries it.
Traces and metrics belong to the opentelemetry skill. Wire logging first (you need logs to debug the rest), then health checks, then tracing.
Patterns
Serilog Setup (Minimal)
using Serilog;
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateBootstrapLogger(); // captures startup failures
try
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSerilog((services, lc) => lc
.ReadFrom.Configuration(builder.Configuration)
.ReadFrom.Services(services)
.Enrich.FromLogContext());
var app = builder.Build();
app.UseSerilogRequestLogging(); // one summary event per request
app.Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Application terminated unexpectedly");
}
finally
{
await Log.CloseAndFlushAsync(); // flush async sinks (Seq, OTLP)
}Why: the bootstrap logger records failures that happen before DI is built. AddSerilog() (not the legacy UseSerilog()) lets the logger resolve services through ReadFrom.Services. Levels, sinks, and overrides live in appsettings.json so they change per environment without a redeploy. Full configuration, sinks, enrichers, destructuring, and filtering are in references/serilog.md.
Message Templates and Source-Generated Logging
// Ad-hoc: named placeholders keep the properties queryable
logger.LogInformation("Order {OrderId} placed by {CustomerId}", orderId, customerId);
// Hot paths and messages reused in several places
public static partial class OrderLogs
{
[LoggerMessage(Level = LogLevel.Information,
Message = "Order {OrderId} created for {CustomerId}")]
public static partial void OrderCreated(this ILogger logger, Guid orderId, Guid customerId);
}
logger.OrderCreated(order.Id, order.CustomerId);Why: the generated method checks IsEnabled first, so a disabled level costs one branch. A named method also gives each event a stable ID and wording, which makes alerts reliable.
Correlation IDs
using Serilog.Context;
internal sealed class CorrelationIdMiddleware(RequestDelegate next)
{
private const string Header = "X-Correlation-Id";
public async Task InvokeAsync(HttpContext context)
{
var correlationId = context.Request.Headers[Header].FirstOrDefault()
?? Guid.NewGuid().ToString("N");
context.Response.Headers[Header] = correlationId;
using (LogContext.PushProperty("CorrelationId", correlationId))
{
await next(context);
}
}
}
// Program.cs: register early so every downstream log carries the ID
app.UseMiddleware<CorrelationIdMiddleware>();Why middleware: the property is pushed once and attaches to every event in the request scope, with no per-call-site plumbing. LogContext needs .Enrich.FromLogContext(). Forward the same header on outgoing HttpClient calls with a DelegatingHandler (see httpclient-factory). Without Serilog, logger.BeginScope(new Dictionary<string, object> { ["CorrelationId"] = id }) does the same job.
Health Checks
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
builder.Services.AddHealthChecks()
.AddNpgSql(builder.Configuration.GetConnectionString("Default")!,
name: "database", tags: ["ready"])
.AddRedis(builder.Configuration.GetConnectionString("Redis")!,
name: "redis", tags: ["ready"]);
app.MapHealthChecks("/health/live", new HealthCheckOptions
{
Predicate = _ => false // no dependency checks: "am I running?"
}).AllowAnonymous();
app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
Predicate = check => check.Tags.Contains("ready")
}).AllowAnonymous();Why two endpoints: liveness failing means "restart me"; readiness failing means "stop sending traffic". Probes come from load balancers and orchestrators, so mark them AllowAnonymous() explicitly. Check package availability with dotnet add package, never pin versions from memory.
Log-Level Strategy
| Level | Use for | Where enabled |
| Debug | Diagnostic detail, payload dumps | Development only |
| Information | Business events: order placed, job completed | Dev and staging; production via namespace overrides |
| Warning | Recoverable anomalies: retry fired, fallback used | Everywhere, production default |
| Error | Failed operations needing attention | Everywhere |
| Critical | App cannot continue | Everywhere |
Why Warning as the production default: framework Information noise at scale costs real money in storage and buries signals. Raise your own namespaces to Information with MinimumLevel.Override (see references/serilog.md). Use TimeProvider, not DateTime.Now, when a log message needs a timestamp you compute yourself; sinks already stamp events.
Anti-patterns
String Interpolation in Log Calls
// BAD: breaks structure, allocates even when the level is disabled
logger.LogInformation($"Order {orderId} created for {customerId}");
// GOOD: message template with named parameters
logger.LogInformation("Order {OrderId} created for {CustomerId}", orderId, customerId);Logging Sensitive Data
// BAD: credentials and PII in logs
logger.LogInformation("Login: {Email} with password {Password}", email, password);
// GOOD: identifiers only; emails, names, IPs, and tokens stay at Debug in development
logger.LogInformation("User {UserId} logged in", userId);One Endpoint for Every Probe
// BAD: all checks run for liveness AND readiness
app.MapHealthChecks("/health");
// GOOD: separate liveness from readiness
app.MapHealthChecks("/health/live", new() { Predicate = _ => false });
app.MapHealthChecks("/health/ready", new() { Predicate = c => c.Tags.Contains("ready") });Skipping CloseAndFlush
// BAD: buffered events from async sinks are lost on exit
app.Run();
// GOOD: flush in finally (see Serilog Setup above)
finally { await Log.CloseAndFlushAsync(); }Static Serilog Log.* Calls in Application Code
// BAD: hidden static dependency, bypasses DI, hard to test
Log.Information("Order {OrderId} created", orderId);
// GOOD: inject ILogger<T>; keep Log.* for Program.cs bootstrap only
public sealed class OrderService(ILogger<OrderService> logger) { }Decision Guide
| Scenario | Recommendation |
| Application logging | ILogger<T> + Serilog via AddSerilog() and appsettings |
| Hot path or reused message | [LoggerMessage] source generator |
| Sinks, enrichers, destructuring, filtering | references/serilog.md |
| Request logging | UseSerilogRequestLogging() |
| Request tracing across services | Correlation ID middleware plus OpenTelemetry |
| Scoped properties (tenant, user) | LogContext.PushProperty() in middleware |
| Distributed tracing, metrics, OTLP | opentelemetry skill |
| Container health | /health/live and /health/ready, probed by the orchestrator |
| Log storage | Seq or Aspire dashboard for development; OTLP backend or Elastic for production |
| Audit trail | Serilog AuditTo (synchronous, failures propagate) |
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

